[JAVA] Check leftmost node of root and root.right / T : O(LogN^2), S : O(1)


  • 0
    J
    class Solution {
        public int countNodes(TreeNode root) {
            if(root == null)
                return 0;
            
            TreeNode cur = root; 
            int left = 0;
            while(cur != null){
                cur = cur.left;
                left++;
            }
            
            cur = root.right;
            int right = 1;
            while(cur != null){
                cur = cur.left;
                right++;
            }
                
            if(left == right){
                return (int)((1 << (left-1)) - 1) + 1 + countNodes(root.right);    
            }
            return (int)((1 << (left-2)) - 1) + 1 + countNodes(root.left);
        }
    }
    

Log in to reply
 

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