码迷,mamicode.com
首页 > 其他好文 > 详细

222. Count Complete Tree Nodes

时间:2016-07-08 23:07:48      阅读:118      评论:0      收藏:0      [点我收藏+]

标签:

/**
 * Definition for a binary tree node.
 * public class TreeNode {
 *     int val;
 *     TreeNode left;
 *     TreeNode right;
 *     TreeNode(int x) { val = x; }
 * }
 */
public class Solution {
    public int countNodes(TreeNode root) {
    
        if(root==null)
            return 0;
        //获取到左右两个深度
        int leftDepth=getLeftDepth(root)+1;
        int rightDepth=getRightDepth(root)+1;
        if(leftDepth==rightDepth)
        {
            
            //这里采用位运算可以让实际那复杂度更加低,如果调用pow计算的话,会超时
            return (2<<(leftDepth-1)) - 1;
            //return (int)Math.pow(2,leftDepth)-1;
        }
        else
        {
            return countNodes(root.left)+countNodes(root.right)+1;
        }
        
        
    }
    
    public int getLeftDepth(TreeNode root)
    {
        int res=0;
        TreeNode temp=root.left;
        while(temp!=null)
        {
            res++;
            temp=temp.left;
            
        }
        return res;
    }
    
    public int getRightDepth(TreeNode root)
    {
        int res=0;
        TreeNode temp=root.right;
        while(temp!=null)
        {
            res++;
            temp=temp.right;
        }
        return res;
        
    }
    
}

 

222. Count Complete Tree Nodes

标签:

原文地址:http://www.cnblogs.com/aguai1992/p/5654724.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!