Getting TLE. Where can I optimize this?


  • 0
    A
    public class Solution 
    {
        public int countNodes(TreeNode root) 
        {
            if(root==null)
                return 0;
            int left = count(root.left);
            int right = count(root.right);
            if(left<=right)
            {
                return ((int)(Math.pow(2, left)-1) + countNodes(root.right) + 1);
            }
            else
            {
                return (countNodes(root.left) + (int)(Math.pow(2, right)-1) + 1);
            }
        }
        
        public static int count(TreeNode root)
        {
            int ctr=0;
            while(root!=null)
            {
                ctr++;
                root = root.left;
            }
            return ctr;
        }
    }

  • 0
    W

    I used the same method as yours but get AC, i think the only difference is that if leftHeight == rightHeight, I return ((1 << leftHeight) - 1) directly.


Log in to reply
 

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