Algorithm/문제풀이

[LeetCode#110] Balanced Binary Tree

gilbert9172 2024. 9. 23. 23:12

 

❒ Description


날짜 2024.09.22 (일)
레벨 Easy
제목 Balanced Binary Tree
링크 https://leetcode.com/problems/balanced-binary-tree/description/
자료구조 그래프
시간 복잡도 O(N)

 

이번 문제를 풀기 위해서는 Height-Balanced Binary Tree에 대한 이해가 필요하다.

 

 

 

 

 

❒ Solution


public void isBalanced(TreeNode root) {
    return depth(root) != -1;
}

public int depth(TreeNode node) {
    if (node == null) return 0;
    int left = depth(node.left);
    int right = depth(node.right);
    if (left == -1 || right < -1 || Math.abs(left - right) > 1) {
        return -1;
    }
    return Math.max(left, right) + 1;
}