One Code 222 a day. The number of nodes in a complete binary tree

insert image description here
Code idea
There are only two cases for a full binary tree:
insert image description here
the left is the first case: the height of the subtree is the same, then the left subtree must be a full binary tree.
On the right is another case: the height of the subtree is different, the right subtree must be full of the binary tree.

code

/**
 * Definition for a binary tree node.
 * struct TreeNode {
 *     int val;
 *     TreeNode *left;
 *     TreeNode *right;
 *     TreeNode(int x) : val(x), left(NULL), right(NULL) {}
 * };
 */
class Solution {
    
    
public:
    int getheight(TreeNode *root){
    
    
        if(!root) return 0;
        return max(getheight(root->left)+1,getheight(root->right)+1);	//其实没必要求右子树高度,但是就当自己练一下模板了。
    }
    int countNodes(TreeNode* root) {
    
    
        //求完全二叉树的节点个数
        if(!root) return 0;                         //空树
        if(!root->left && !root->right) return 1;   //只有一个根结点
        int sum = 0;
        while(root){
    
                                    //根不为空,意味着没判断到最后
            int root_h = getheight(root),l_h = getheight(root->left),r_h = getheight(root->right);
            if(l_h == r_h){
    
                             //子树高度相同意味左子树一定为满二叉树
                sum += pow(2,l_h);                  //加上左子树节点个数加根节点
                root=root->right;
            }
            else{
    
                                       //子树高度不同意味右子树一定为满二叉树
                sum += pow(2,r_h);
                root=root->left;
            }
        }
        return sum;
    }
};

Guess you like

Origin blog.csdn.net/qq_41746268/article/details/108280697