博客
关于我
强烈建议你试试无所不能的chatGPT,快点击我
Count Complete Tree Nodes
阅读量:2341 次
发布时间:2019-05-10

本文共 1324 字,大约阅读时间需要 4 分钟。

果然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;}

转载地址:http://lbuvb.baihongyu.com/

你可能感兴趣的文章
linux 开发机服务器和hdfs集群中断程序命令
查看>>
python 文件操作(遍历、复制、生成文件名)
查看>>
运行.py 文件出现ImportError: No module named 'xxx'问题
查看>>
Mac Matlab安装破解教程 + 环境变量配置 (附软件下载)
查看>>
python图像旋转
查看>>
Mac 删除.DS_Store文件且不再生
查看>>
【剑指offer python】面试题3:二维数组中的查找
查看>>
【剑指offer python】面试题4:替换空格
查看>>
【剑指offer python】面试题5:从头到尾打印链表
查看>>
【剑指offer python】面试题7:用两个栈实现队列
查看>>
【剑指offer python】面试题8:旋转数组的最小数字
查看>>
【剑指offer python】面试题9:斐波那契数列
查看>>
【剑指offer python】面试题11:数值的整数次方
查看>>
【剑指offer python】面试题14:调整数组顺序使奇数位于偶数前面
查看>>
【剑指offer python】面试题15:链表中倒数第k个结点
查看>>
【剑指offer python】面试题19:二叉树的镜像
查看>>
【剑指offer python】数字在排序数组中出现的次数
查看>>
【剑指offer python】二叉树的深度
查看>>
【剑指offer python】判断平衡二叉树
查看>>
【剑指offer python】数组中只出现一次的数字
查看>>