首页 > 其他 > 详细

[LeetCode]Count Complete Tree Nodes

时间:2015-11-30 13:04:09      阅读:254      评论:0      收藏:0      [点我收藏+]

这个题目最开始算2的次方用了Math.pow,发现超时,改用1<<left之后通过。看来pow的开销是很大的啊

public class Solution {
    public int countNodes(TreeNode root) {
       return helper(root);
    }
    public int helper(TreeNode root) {
        if (root == null) {
            return 0;
        }
        int left = 0;
        int right = 0;
        TreeNode p = root;
        while (p != null) {
            left ++;
            p = p.left;
        }
        p = root;
        while (p != null) {
            right ++;
            p = p.right;
        }   
        if (left == right) {
            return (1 << left) - 1;
        } else {
            return helper(root.left) + helper(root.right) + 1;
        }
    }
}

 

[LeetCode]Count Complete Tree Nodes

原文:http://www.cnblogs.com/vision-love-programming/p/5006842.html

(0)
(0)
   
举报
评论 一句话评论(0
关于我们 - 联系我们 - 留言反馈 - 联系我们:wmxa8@hotmail.com
© 2014 bubuko.com 版权所有
打开技术之扣,分享程序人生!