LeetCode222. Count Complete Tree Nodes (完全二叉树节点计数技巧)

Given a complete binary tree, count the number of nodes.

Note:

Definition of a complete binary tree from Wikipedia:
In a complete binary tree every level, except possibly the last, is completely filled, and all nodes in the last level are as far left as possible. It can have between 1 and 2h nodes inclusive at the last level h.

Example:

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

Output: 6

解法
一开始采用二叉树遍历的方法,得到了TLE

class Solution {
    int preOrder(TreeNode* root) {
       if(root) {
           int left = preOrder(root->left);
           int right = preOrder(root->right);
           return left+right+1;
       } 
       return 0;
    }
public:
    int countNodes(TreeNode* root) {
        return preOrder(root);
    }
};

后来看到了题干,规定是完全二叉树,想到了完全二叉树的形状,用了类似的方法,也得到了TLE。看了别人的博客,得知,要想得到AC必须不能采取全部遍历的方法,必须要利用完全二叉树的性质。

得到一个技巧:①如果某个子树是满二叉树,则通过公式返回该子树的节点数,不继续遍历下去。
②如果该子树不是满二叉树,而递归处理左右子树,直到出现满二叉树的情况。

判断一颗完全二叉树是不是满二叉树的方法:左节点不断深入得到一个深度,右几点不断深入得到另外一个深度,判断两个深度是不是相同,如果相同则为满二叉树。

代码如下:

class Solution {
    int getLeftdep(TreeNode* root) {
        int cnt=1;
        if(root==NULL) return 0;
        while(root->left) {
            root = root->left;
            cnt++;
        }
        return cnt;
    }
    
    int getRightdep(TreeNode* root) {
        int cnt = 1;
        if(root==NULL) return 0;
        while(root->right) {
            root=root->right;
            cnt++;
        }
        return cnt;
    }
public:
    int countNodes(TreeNode* root) {
        if(root==NULL) return 0; 
        int dep1 = getLeftdep(root);
        int dep2 = getRightdep(root);
        if(dep1==dep2) // 满二叉树
            return (1<<dep1)-1;
        return 1+countNodes(root->left)+countNodes(root->right);
    }
};

猜你喜欢

转载自blog.csdn.net/qq_26973089/article/details/83625268