Count Complete Tree Nodes

题目链接

果然java不适合做acm。我看到上面一个人的答案写的代码,只是我把他的c++写成了java。于是碰到一个大的数组就超时了。。我确定我的代码和他的代码是一样的。所以只能直接贴代码了,有人都开始用java调用c++来执行了。也不行看来真的是java的速度问题。

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 result=1;
       int nLeft=deep(root.left);
       int nRight=deep(root.right);
       if(nLeft==nRight)
       {
        result+=Math.pow(2, nLeft)-1;

        result+=countNodes(root.right);

       }
       else
       {

        result+=Math.pow(2, nRight)-1;
        result+=countNodes(root.left);
       }


       return result;



   }


   public int deep(TreeNode root)
   {
    if(root==null)
    {
        return 0;   
    }

    int n=1;
    while(root.left!=null)
    {
        n++;
        root=root.left;
    }
    return n;

   }
}

c++版代码

public class Solution {
public int countNodes(TreeNode root) {
    if(root==null) return 0;
    int l = getLeftCount(root.left);
    int r = getLeftCount(root.right);
    if(l==r){
        return  (int)Math.pow(2,l)+countNodes(root.right);
    }else{
        return  (int)Math.pow(2,r)+countNodes(root.left);
    }
}

public int getLeftCount(TreeNode n){
    int count = 0;
    while(n!=null){
        n = n.left;
        count++;
    }
    return count;
}

你可能感兴趣的:(Count Complete Tree Nodes)