• LeetCode222


        public static int pow2(int x){
            if(x==1)
                return 1;
            else{
                /**
                 * 必须用一个数来保存左移的结果
                 * 否则not a statement
                 * 移x位,等于乘以x个2
                 * 2 《《 x
                 * 这样就是2^x+1次方了
                 */
                int num = 0;
                num = 1 << x ;
                return num-1;
            }
        }
        /**
         *
         * 对于一个节点node,计算它最左端的节点到node的深度为leftDepth,计算它最右端的节点到node的深度是rightDepth;
            如果leftDepth和rightDepth相等,那么以node为根节点的树是一棵满二叉树,此时以node为根节点的树的节点个数是pow(2,leftDepth)-1;
            如果leftDepth和rightDepth不相等,递归求解node的左子树的节点数和右子树的节点数。
         */
        public int countNodes(TreeNode root) {
    
            if(root==null)
                return 0;
    
            int leftDepth = 0;
            int rightDepth = 0;
    
            /**
             * 统计左边子树高度
             */
            for(TreeNode node = root;node!=null;node=node.left)
                leftDepth++;
    
            for(TreeNode node = root;node!=null;node=node.right)
                rightDepth++;
    
    
            if(leftDepth==rightDepth){
                return pow2(leftDepth);
            } else{
    
                return 1+countNodes(root.left)+countNodes(root.right);
    
            }
    
    
    
        }
  • 相关阅读:
    设计模式-观察者模式
    获取ubuntu中软件包的有用地址
    vim 简单命令
    adb logcat 日志过滤
    shell编程——
    shell编程——参数传递
    Chromecast
    linux 广播
    【转】Git命令解说
    linux 多播
  • 原文地址:https://www.cnblogs.com/weizhibin1996/p/9192613.html
Copyright © 2020-2023  润新知