I am trying to do the Balanced Tree question on Leetcode where you return true only if height of left subtree - height of right subtree <= 1. Why is the depth of the left subtree returning a 2 when it should return 4? Is there something I am interpreting wrongly? I attached a picture of the tree at the bottom.
Input: [1,2,2,3,3,null,null,4,4,null,null,5,5]
Output: True (because left subtree is returning 2 instead of 4)
Expected Output: False
Print Statements:
left subtree: 2
right subtree: 1
result: 1 (left subtree - right subtree)
/**
* Definition for a binary tree node.
* public class TreeNode {
* int val;
* TreeNode left;
* TreeNode right;
* TreeNode() {}
* TreeNode(int val) { this.val = val; }
* TreeNode(int val, TreeNode left, TreeNode right) {
* this.val = val;
* this.left = left;
* this.right = right;
* }
* }
*/
class Solution {
public boolean isBalanced(TreeNode root) {
// 1 2 2 3 3 4 4
//
if (root == null) return true;
System.out.println("left subtree: " + findDepth(root.left,1));
System.out.println("right subtree: " + findDepth(root.right,1));
System.out.println("result: " + Math.abs(findDepth(root.left,1) - findDepth(root.right, 1)));
if ( Math.abs(findDepth(root.left,1) - findDepth(root.right, 1)) <= 1) return true;
return false;
}
public static int findDepth(TreeNode root, int count) {
if (root == null) return count;
if (root.left != null) {
count++;
findDepth(root.left, count);
}
if(root.left == null && root.right == null) return count;
return count;
}
}