110. Balanced Binary Tree
Solution#
var dfs = function(root) {
if (!root) {
return [true, 0];
}
if (!root.left && !root.right) {
return [true, 1];
}
const left = dfs(root.left);
const right = dfs(root.right);
const balanced = left[0] && right[0] && (Math.abs(left[1] - right[1]) <= 1);
return [balanced, 1 + Math.max(left[1], right[1])];
}
/**
* 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 dfs(root)[0];
};
Complexity#
- Time Complexity: O(N), because we might traverse every node.
- Space Complexity: O(N), because of the implicit call stack to
dfs()
.
All Solutions