Videos
Hey guys, I've been trying to pass the balanced binary tree LC and I couldn't figure it out myself, so I referenced a recursive solution. I'm having a hard time wrapping my head around the solution and why it works. The code is below:
class Solution {
public:
bool isBalanced(TreeNode* root) {
int height = 0;
return dfs(root, height);
}
public:
bool dfs(TreeNode* root, int &height) {
if(root == NULL){
height = -1;
return true;
}
int left = 0;
int right = 0;
if(!(dfs(root -> left, left)) || !(dfs(root -> right, right))){
return false;
}
if(abs(left - right) > 1){
return false;
}
height = 1 + max(left, right);
return true;
}
};
I'm kinda confused as to how left and right are used. To my understanding, the first if statement is making sure it's not an empty tree, and the height = -1 is useless? And the coder basically declared the left and right int variables to keep track of the depth of the tree for both the left and the right nodes. The next if statement iterates through the tree, and left/right are used as the new height for the next node, and the next if statement tells us whether the condition of being a balanced tree good or not. Lastly, I believe the height is updated by 1 + the deepest node because we go down one node further? And if the function goes up the call stack and returns true for all of them, the node is balanced. However, I'm not too sure how left and right are updated since I only see them set equal to 0. I guess I'm just not quite sure how the height and everything is updated. Sorry if my understanding is really confusing I just find it really hard to wrap my head around recursion, any help would be great thanks!