leetcode 222.Count Complete Tree Nodes

这道题我一开始用的是dfs,遍历一个节点就加1,结果数据量庞大的情况下超时。后来看了一下leetcode的标准解法,用的办法是分治法,将二叉树不断地分解为两个小二叉树,每次都计算该二叉树最大左深度ld和最大右深度rd,当ld==rd的时候直接 return pow(2, ld) - 1即可。

class Solution {
public:
    int countNodes(TreeNode* root) {
        return countNodesWithDepth(root, -1, -1);
    }

    // By passing ld and rd to lower subtree, avoid repeated caculation
    int countNodesWithDepth(TreeNode* root, int ld, int rd){
        if(ld==-1)
            ld = ldepth(root);
        if(rd==-1)
            rd = rdepth(root);
        if(ld==rd)
            return pow(2, ld) - 1;
        else
            return 1 + countNodesWithDepth(root->left, ld-1, -1) + countNodesWithDepth(root->right, -1, rd-1);
    }

    int rdepth(TreeNode* root) {
        if(root==NULL)
            return 0;
        else
            return 1 + rdepth(root->right);  
    }

    int ldepth(TreeNode* root){
        if(root==NULL)
            return 0;
        else
            return 1 + ldepth(root->left);
    }
};

猜你喜欢

转载自blog.csdn.net/qq_36946274/article/details/80872864