Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

222. Count Complete Tree Nodes #229

Open
Tcdian opened this issue Jun 23, 2020 · 1 comment
Open

222. Count Complete Tree Nodes #229

Tcdian opened this issue Jun 23, 2020 · 1 comment
Labels

Comments

@Tcdian
Copy link
Owner

Tcdian commented Jun 23, 2020

222. Count Complete Tree Nodes

给出一个 完全二叉树,求出该树的节点个数。

Note

完全二叉树的定义如下:在完全二叉树中,除了最底层节点可能没填满外,其余每层节点数都达到最大值,并且最下面一层的节点都集中在该层最左边的若干位置。若最底层为第 h 层,则该层包含 1~ 2h 个节点。

Example

Input: 
    1
   / \
  2   3
 / \  /
4  5 6

Output: 6
@Tcdian
Copy link
Owner Author

Tcdian commented Jun 23, 2020

Solution

  • JavaScript Solution
/**
 * Definition for a binary tree node.
 * function TreeNode(val, left, right) {
 *     this.val = (val===undefined ? 0 : val)
 *     this.left = (left===undefined ? null : left)
 *     this.right = (right===undefined ? null : right)
 * }
 */
/**
 * @param {TreeNode} root
 * @return {number}
 */
var countNodes = function(root) {
    if (root === null) {
        return 0;
    }
    const leftDepth = countDepth(root.left);
    const rightDepth = countDepth(root.right);
    if (leftDepth === rightDepth) {
        return 1 + countNodes(root.right) + (1 << leftDepth) - 1;
    } else {
        return 1 + countNodes(root.left) + (1 << rightDepth) - 1;
    }
};

function countDepth(patrol) {
    let depth = 0;
    while(patrol !== null) {
        depth++;
        patrol = patrol.left;
    }
    return depth;
}
  • TypeScript Solution
/**
 * Definition for a binary tree node.
 * class TreeNode {
 *     val: number
 *     left: TreeNode | null
 *     right: TreeNode | null
 *     constructor(val?: number, left?: TreeNode | null, right?: TreeNode | null) {
 *         this.val = (val===undefined ? 0 : val)
 *         this.left = (left===undefined ? null : left)
 *         this.right = (right===undefined ? null : right)
 *     }
 * }
 */

function countNodes(root: TreeNode | null): number {
    if (root === null) {
        return 0;
    }
    const leftDepth = countDepth(root.left);
    const rightDepth = countDepth(root.right);
    if (leftDepth === rightDepth) {
        return 1 + countNodes(root.right) + (1 << leftDepth) - 1;
    } else {
        return 1 + countNodes(root.left) + (1 << rightDepth) - 1;
    }
};

function countDepth(patrol: TreeNode | null): number {
    let depth = 0;
    while(patrol !== null) {
        depth++;
        patrol = patrol.left;
    }
    return depth;
}

@Tcdian Tcdian removed the Classic label Jul 30, 2021
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
Projects
None yet
Development

No branches or pull requests

1 participant