Post

[LeetCode 110] Balanced Binary Tree

LeetCode 110 (Java)
[Balanced Binary Tree] 문제 풀이

[LeetCode 110] Balanced Binary Tree

문제 바로가기


Description


Given a binary tree, determine if it is height-balanced.


Example 1


  • Input: root = [3,9,20,null,null,15,7]
  • Output: true


Example 2


  • Input: root = [1,2,2,3,3,null,null,4,4]
  • Output: false


Example 3


  • Input: root = []
  • Output: true


Constraints


  • The number of nodes in the tree is in the range [0, 5000].
  • -10^4 <= Node.val <= 10^4







Code


내 제출


1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
/**
 * Definition for a binary tree node.
 * public class TreeNode {
 *     int val;
 *     TreeNode left;
 *     TreeNode right;
 *     TreeNode() {}
 *     TreeNode(int val) { this.val = val; }
 *     TreeNode(int val, TreeNode left, TreeNode right) {
 *         this.val = val;
 *         this.left = left;
 *         this.right = right;
 *     }
 * }
 */
class Solution {
    public boolean isBalanced(TreeNode root) {
                return height(root) >= 0;
    }

        private int height(TreeNode root) {
        if (root == null) {
            return 0;
        }
        int l = height(root.left);
        int r = height(root.right);
        if (l == -1 || r == -1 || Math.abs(l - r) > 1) {
            return -1;
        }
        return 1 + Math.max(l, r);
    }
}


RuntimeMemory
0 ms44.9 MB


다른 풀이


1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
/**
 * Definition for a binary tree node.
 * public class TreeNode {
 *     int val;
 *     TreeNode left;
 *     TreeNode right;
 *     TreeNode() {}
 *     TreeNode(int val) { this.val = val; }
 *     TreeNode(int val, TreeNode left, TreeNode right) {
 *         this.val = val;
 *         this.left = left;
 *         this.right = right;
 *     }
 * }
 */
class Solution {
    public boolean isBalanced(TreeNode root) {
        if (root == null) {
            return true;
        }

        int leftDepth = getDepth(root.left);
        int rightDepth = getDepth(root.right);

        return (leftDepth - rightDepth <= 1 &&
            leftDepth - rightDepth >= -1) && 
            isBalanced(root.left) &&
            isBalanced(root.right);
    }

    private int getDepth (TreeNode node) {
        if (node == null) {
            return 0;
        }

        return 1 + Math.max(getDepth(node.left) ,getDepth(node.right));
    }
}


Reference


  • https://github.com/doocs/leetcode/blob/main/solution/0100-0199/0110.Balanced%20Binary%20Tree/Solution.java
This post is licensed under CC BY 4.0 by the author.