-
Notifications
You must be signed in to change notification settings - Fork 1
Expand file tree
/
Copy pathLC110.cpp
More file actions
88 lines (66 loc) · 2.01 KB
/
LC110.cpp
File metadata and controls
88 lines (66 loc) · 2.01 KB
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
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
/*
110. Balanced Binary Tree
Given a binary tree, determine if it is height-balanced
Input: root = [3,9,20,null,null,15,7]
Output: true
*/
class Solution {
public:
bool isBalanced(TreeNode* root) {
return checkHeight(root) != -1;
}
private:
int checkHeight(TreeNode* node) {
if (!node) return 0;
int leftHeight = checkHeight(node->left);
if (leftHeight == -1) return -1;
int rightHeight = checkHeight(node->right);
if (rightHeight == -1) return -1;
if (abs(leftHeight - rightHeight) > 1) return -1;
return max(leftHeight, rightHeight) + 1;
}
};
// Iterative solution
#include <iostream>
#include <stack>
#include <unordered_map>
#include <cmath>
using namespace std;
struct TreeNode {
int val;
TreeNode *left, *right;
TreeNode(int x) : val(x), left(nullptr), right(nullptr) {}
};
class Solution {
public:
bool isBalanced(TreeNode* root) {
if (!root) return true;
unordered_map<TreeNode*, int> heightMap;
unordered_map<TreeNode*, bool> visited;
stack<TreeNode*> stk;
stk.push(root);
while (!stk.empty()) {
TreeNode* node = stk.top();
if (!node) {
stk.pop();
continue;
}
if ((!node->left || visited[node->left]) &&
(!node->right || visited[node->right])) {
stk.pop();
int leftHeight = node->left ? heightMap[node->left] : 0;
int rightHeight = node->right ? heightMap[node->right] : 0;
if (abs(leftHeight - rightHeight) > 1)
return false;
heightMap[node] = 1 + max(leftHeight, rightHeight);
visited[node] = true;
} else {
if (node->right && !visited[node->right])
stk.push(node->right);
if (node->left && !visited[node->left])
stk.push(node->left);
}
}
return true;
}
};