A height-balanced binary tree is a binary tree in which the depth of the two subtrees of every node never differs by more than one.
이진 트리에서 높이 균형이란, 각 서브 트리의 높이 차이가 1 이하인 상태를 말한다. 즉, 트리의 각 서브 트리에 대해 왼쪽 서브 트리와 오른쪽 서브 트리의 높이 차이가 1 이하여야 한다.
class Solution:
def isBalanced(self, root: Optional[TreeNode]) -> bool:
self.isHeightBalanced = True
def dfs(node, height = 0):
if not node:
return height
height += 1
left, right = dfs(node.left, height), dfs(node.right, height)
if abs(left - right) > 1:
self.isHeightBalanced = False
return max(left, right)
dfs(root)
return self.isHeightBalanced
const isBalanced = (root) => {
let isHeightBalanced = true;
const dfs = (node, height = 0) => {
if (!node) {
return height;
}
height++;
let [left, right] = [dfs(node.left, height), dfs(node.right, height)];
if (Math.abs(left - right) > 1) {
isHeightBalanced = false;
}
return Math.max(left, right);
};
dfs(root);
return isHeightBalanced;
};