Java solution with Recursion by comparing the left height with the right height.


  • 1
    public class Solution {
    public int countNodes(TreeNode root) {
        return getNodes(root,-1,-1);
    }
    private int getNodes(TreeNode root, int lh, int rh){
        
        if(lh==-1){
            lh=0;
            TreeNode tn=root;
            while(tn!=null){
                lh++;
                tn=tn.left;
            }
        }
        if(rh==-1){
            rh=0;
            TreeNode tn=root;
            while(tn!=null){
                rh++;
                tn=tn.right;
            }
        }
        if(lh==rh) return (1<<lh)-1;
        return 1+getNodes(root.left,lh-1,-1)+getNodes(root.right,-1,rh-1);
    }
    

    }


Log in to reply
 

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