Fork me on GitHub

Leetcode 222:完全二叉树的节点个数

题目

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

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

思路

1.如果一棵二叉树是完全二叉树,那么二叉树最大深度和右子树的最大深度是相同的话,那么根节点的左子树一定是一棵满二叉树,利用公式即可求出根节点的左子树的节点加上根节点的节点数量。
2.如果一棵二叉树是完全二叉树,那么二叉树最大深度和右子树的最大深度是不同的话(实际情况就是二叉树的最大深度比其右子树的最大深度大1),那么右子树一定是深度 为二叉树深度减2的满二叉树。
由上述内容可知,一棵完全二叉树左右子树中至少一个是满二叉树。

题解

/**
 * Definition for a binary tree node.
 * struct TreeNode {
 *     int val;
 *     TreeNode *left;
 *     TreeNode *right;
 *     TreeNode(int x) : val(x), left(NULL), right(NULL) {}
 * };
 */
//https://www.jianshu.com/p/62db7c855e44
class Solution {
private:
    int height(TreeNode* root){
        if(root == NULL)
            return -1;
        while(root != NULL)
            return height(root->left) + 1;
    }
public:
    int countNodes(TreeNode* root) {
        int h=height(root);
        int nums=0;
        while(root!=NULL){
            if(h-1==height(root->right)){
                nums+=1<<h; //相当于pow(2,h - 1)
                root=root->right;
            }
            else{
                nums+=1<<h-1;
                root=root->left;
            }
            h--;
        }
        return nums;
    }
};

reference

posted @ 2019-05-13 11:17  ranjiewen  阅读(1035)  评论(0编辑  收藏  举报