Home LeetCode - 110. Balanced Binary Tree
Post
Cancel

LeetCode - 110. Balanced Binary Tree

110. Balanced Binary Tree - easy

문제

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

For this problem, a height-balanced binary tree is defined as:

a binary tree in which the left and right subtrees of every node differ in height by no more than 1.

제한사항

입출력 예

1
2
3
4
5
6
7
8
9
10
11
Example 1:

Given the following tree [3,9,20,null,null,15,7]:

    3
   / \
  9  20
    /  \
   15   7

Return true.
1
2
3
4
5
6
7
8
9
10
11
12
13
Example 2:

Given the following tree [1,2,2,3,3,null,null,4,4]:

       1
      / \
     2   2
    / \
   3   3
  / \
 4   4

Return false.

풀이

  • Tree, DFS
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
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
/**
 * Definition for a binary tree node.
 * struct TreeNode {
 *     int val;
 *     TreeNode *left;
 *     TreeNode *right;
 *     TreeNode() : val(0), left(nullptr), right(nullptr) {}
 *     TreeNode(int x) : val(x), left(nullptr), right(nullptr) {}
 *     TreeNode(int x, TreeNode *left, TreeNode *right) : val(x), left(left), right(right) {}
 * };
 */
class Solution {
public:
    
    int dfs(TreeNode* root) {
        if (!root) {
            return 0;    
        }

        int depth = 0;
        std::stack<std::pair<TreeNode*, int>> s;
        s.push({root, 1});
        
        while (!s.empty()) {
            auto node = s.top();
            s.pop();
            
            if (!node.first->left && !node.first->right) {
                depth = std::max(depth, node.second);
            }
            
            if (node.first->left) {
                s.push({node.first->left, node.second + 1});
            }
            
            if (node.first->right) {
                s.push({node.first->right, node.second + 1});
            }
        }
        
        return depth;
    }
    
    bool isBalanced(TreeNode* root) {
        if (!root || (!root->left && !root->right)) {
            return true;
        }
        
        bool left = isBalanced(root->left);
        bool right = isBalanced(root->right);
        
        int leftDepth = dfs(root->left);
        int rightDepth = dfs(root->right);
        int val = std::abs(leftDepth - rightDepth);
        
        return val > 1 ? false : true &&
                left &&
                right;
    }
};
This post is licensed under CC BY 4.0 by the author.