My Simple DFS Java solution


  • 2
    Q
    public class Solution {
        private boolean balanced = true;
    	public boolean isBalanced(TreeNode root) {
            findDepth(root, 1);
            return balanced;
        }
            
       private int findDepth(TreeNode node, int level){
    	    if (!balanced || node == null){
    	   		return level-1;
    	   	}
            int depthL = findDepth(node.left, level+1);
            int depthR = findDepth(node.right, level+1);
            int max = Math.max(depthL, depthR);
            int min = Math.min(depthL, depthR);
            if (max-min > 1){
                balanced = false;
            }
            return max;
        }
    }

  • 0

    You can use Math.abs(depthL - depthR)


  • 0
    This post is deleted!

  • 0

    Along with using Math.abs() , You can also have 1 more modification
    as shown ..

        private int findDepth(TreeNode node, int level)
    {
    
     if (node == null)
     return level-1; 
    
     int depthL =0 ,depthR=0;
    
     if(balanced)
    { 
    depthL = findDepth(node.left, level+1); 
    depthR = findDepth(node.right, level+1); 
    
    if (Math.abs(depthL,depthR) > 1)
     balanced = false; 
     } 
    return depthL>depthR?depthL:depthR; 
    }

Log in to reply
 

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