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

完全二叉树的节点个数 #140

Open
louzhedong opened this issue Mar 21, 2019 · 0 comments
Open

完全二叉树的节点个数 #140

louzhedong opened this issue Mar 21, 2019 · 0 comments

Comments

@louzhedong
Copy link
Owner

习题

出处 LeetCode 算法第222题

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

说明:

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

示例:

输入: 
    1
   / \
  2   3
 / \  /
4  5 6

输出: 6

思路

递归计算左右子树的值,进行累加

解答

/**
 * @param {TreeNode} root
 * @return {number}
 */
var countNodes = function(root) {
    var count = 0;
    if (!root) {
        return 0;
    }
    count    ;
    count  = countNodes(root.left);
    count  = countNodes(root.right);
    return count;
};
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

No branches or pull requests

1 participant