I'm working on the Leetcode problem 110. Balanced Binary Tree and I'm confused on how the subtree values are getting populated when doing recursion. After looking at a few solutions, here's the code I have in Javascript:
/**
* Definition for a binary tree node.
* function TreeNode(val, left, right) {
* this.val = (val===undefined ? 0 : val)
* this.left = (left===undefined ? null : left)
* this.right = (right===undefined ? null : right)
* }
*/
/**
* @param {TreeNode} root
* @return {boolean}
*/
var isBalanced = function(root) {
return treeHeight(root) !== -1;
};
function treeHeight(root){
if(!root) return 0;
const leftSubTree = treeHeight(root.left);
const rightSubTree = treeHeight(root.right);
if(leftSubTree === -1 || rightSubTree === -1) return -1; // how can recursion lead to either subtree being -1? At this point I don't know how this can be true other than "that's just how recursion works"
if(Math.abs(leftSubTree - rightSubTree) > 1) return -1; // how are the values of either subtree even obtained here?
return Math.max(leftSubTree, rightSubTree) + 1; // same as the previous question. how do either subtree even get values?
}
I'm trying to understand the following lines:
if(leftSubTree === -1 || rightSubTree === -1) return -1; // how can recursion lead to either subtree being -1? At this point I don't know how this can be true other than "that's just how recursion works"
if(Math.abs(leftSubTree - rightSubTree) > 1) return -1; // how are the values of either subtree even obtained here?
return Math.max(leftSubTree, rightSubTree) + 1; // same as the previous question. how do either subtree even get values?
I get that the recursion will traverse down the tree on the left side and the rightside. I don't get how through recursion, the subtrees values are getting computed. Can someone explain it please?

root.leftas the argument. It keeps recursing until it gets to a leaf where the value isnull.treeHeight(root.left). What value is getting computed at each recursive call? I only know the last call will be 0 because that is the base case. How are the rest of the values getting computed?