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);
    }
};
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值