Simple Typescript w/ Annotations
Intuition\nBecause balance depends on the left-max-depth and right-max-depth of every node, I know that every node must be traversed (DFS sounds good).\n\n\n# A
# Intuition\nBecause balance depends on the left-max-depth and right-max-depth of every node, I know that every node must be traversed (DFS sounds good).\n\n\n# Approach\nSo DFS every node.\n\nAt every level, we want to return the max-depth to the previous recursive call, so we return Math.max(maxLeftDepth, maxRightDepth).\nBUT you should add 1 to it to account for the depth of the current node we\'re on. So `Math.max(maxLeftDepth, maxRightDepth) + 1`\nThis passes max-depth up the chain of recursion.\n\nAfter maxLeftDepth and maxRightDepth are checked, we check to see if they differ by more than 1 -> `Math.abs(maxLeftDepth - maxRightDepth) > 1` and set a global variable `imabalanceFound` to true if that\'s the case.\n\nBase case is when a node is not reached, so return 0 to indicate depth.\n\nAt end of function call, return opposite of global variable `imbalanceFound`\n\n# Complexity\n- Time complexity:\nO(n), since every node is visited\n\n- Space complexity:\nO(1) since, only 1 variable required to hold boolean\n\n# Upvote if helpful, thanks y\'all\n\n# Code\n```\n/**\n * Definition for a binary tree node.\n * class TreeNode {\n *     val: number\n *     left: TreeNode | null\n *     right: TreeNode | null\n *     constructor(val?: number, left?: TreeNode | null, right?: TreeNode | null) {\n *         this.val = (val===undefined ? 0 : val)\n *         this.left = (left===undefined ? null : left)\n *         this.right = (right===undefined ? null : right)\n *     }\n * }\n */\n\nfunction isBalanced(root: TreeNode | null): boolean {\n    let imbalanceFound = false;\n\n    function dfs (thisNode) {\n        if(!thisNode) return 0;\n\n        else if(!imbalanceFound) { //prevents unnecessary recursion\n\n            let leftDepth = dfs(thisNode.left)\n            let rightDepth = dfs(thisNode.right)\n\n            //stops the recursive calls if imbalance found\n            if(Math.abs(leftDepth - rightDepth) > 1) imbalanceFound = true\n            \n            //pass up current depth + max below it\n            return 1 + Math.max(leftDepth, rightDepth)\n        \n        }\n    }\n    dfs(root);\n\nreturn !imbalanceFound\n};\n\n\n\n```
['Depth-First Search', 'TypeScript', 'JavaScript']