PS/LeetCode

LeetCode / Tree / 110번 / Balanced Binary Tree / JS

KimMinJun 2023. 4. 28. 17:31

< 문제 바로가기 >

 

Balanced Binary Tree - LeetCode

Can you solve this real interview question? Balanced Binary Tree - Given a binary tree, determine if it is height-balanced.   Example 1: [https://assets.leetcode.com/uploads/2020/10/06/balance_1.jpg] Input: root = [3,9,20,null,null,15,7] Output: true Exam

leetcode.com

 

< 문제 간단설명 >

균형잡힌 이진트리인지 boolean 값으로 반환하는 문제이다. 여기서 균형잡힌 이진트리란, 왼쪽과 오른쪽의 subtree의 depth가 1보다 크게, 즉 2이상 차이나지 않는 트리이다.

 

/**
 * 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) {
    let result = true;

    const DFS = (node, height) => {
        // 빈 subtree라면 height 0 반환
        if(node === null) {
            return 0;
        }

        let leftHeight = DFS(node.left, height + 1);
        let rightHeight = DFS(node.right, height + 1);

        // height 차이가 1보다 크다면 false
        if(Math.abs(leftHeight - rightHeight) > 1) {
            result = false;
        }

        // 왼쪽과 오른쪽중 큰 height에 + 1을 해서 반환
        // backtracking 을 하면서 높이를 구해줌
        return Math.max(leftHeight, rightHeight) + 1;
    }

    DFS(root, 0);

    return result;
};