Why getting time out for a two node input [1,2]


  • 0
    P
    public int countNodes(TreeNode root) {
            if (root == null) {
    			return 0;
    		}
    		if(root.left==null && root.right==null){
    			return 1;
    		}
    		double height = count(root);
    		int sum = 0;
    		while(height>=0)
    		{
    			sum=sum+ (int)Math.pow(2, height);
    		}
    		return sum;
    		
        }
        public static int count(TreeNode root) {
    		if (root == null) {
    			return 0;
    		}
    		int rightCount = count(root.right);
    		return rightCount+1;
    		}

  • 0
    W

    while(height>=0)
    {
    sum=sum+ (int)Math.pow(2, height);
    }

    Your height is not changing.
    It is an infinite loop.

    And your solution is wrong.
    A complete tree does not have to fill the last level.


Log in to reply
 

Looks like your connection to LeetCode Discuss was lost, please wait while we try to reconnect.