zoukankan      html  css  js  c++  java
  • 222. Count Complete Tree Nodes

    /**
     * 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;
            
        }
        
    }
  • 相关阅读:
    4.23计算机网络
    CF436F Banners
    CF1467C Three Bags
    LG P3247 [HNOI2016]最小公倍数
    LG P5473 [NOI2019] I 君的探险
    LG P3261 [JLOI2015]城池攻占
    LG P4149 [IOI2011]Race
    LG P3181 [HAOI2016]找相同字符
    SP7258 SUBLEX
    SP1811 LCS
  • 原文地址:https://www.cnblogs.com/aguai1992/p/5654724.html
Copyright © 2011-2022 走看看