Skip to main content

Leetcode - 110. Balanced Binary Tree

· One min read

https://leetcode.com/problems/balanced-binary-tree/

Solution 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) {
if (root === null) {
return true;
}
return checkDepth(root) !== false;
};

const checkDepth = (node) => {
if (node === null) {
return 0;
}

// 각각 false 혹은 왼쪽/오른쪽 자식의 최대 깊이
const left = checkDepth(node.left);
const right = checkDepth(node.right);

if (left === false || right === false || Math.abs(left - right) > 1) {
return false;
}

// 트리의 가장 깊은 길이를 return
return Math.max(left, right) + 1;
};