Skip to content

Commit dc31034

Browse files
[CPP] 110. Balanced Binary Tree
1 parent a22757f commit dc31034

File tree

1 file changed

+28
-0
lines changed

1 file changed

+28
-0
lines changed

cpp/110-Balanced-Binary-Tree.cpp

Lines changed: 28 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,28 @@
1+
/**
2+
* Definition for a binary tree node.
3+
* struct TreeNode {
4+
* int val;
5+
* TreeNode *left;
6+
* TreeNode *right;
7+
* TreeNode() : val(0), left(nullptr), right(nullptr) {}
8+
* TreeNode(int x) : val(x), left(nullptr), right(nullptr) {}
9+
* TreeNode(int x, TreeNode *left, TreeNode *right) : val(x), left(left), right(right) {}
10+
* };
11+
*/
12+
class Solution {
13+
public:
14+
15+
int getHeight(TreeNode* root, unordered_map<TreeNode*, int>& umap) {
16+
if (root==NULL) return 0;
17+
if (umap.find(root) != umap.end()) return umap[root];
18+
int res = max(getHeight(root->left, umap), getHeight(root->right, umap))+1;
19+
umap[root] = res;
20+
return res;
21+
}
22+
bool isBalanced(TreeNode* root) {
23+
unordered_map<TreeNode*, int> umap;
24+
if (root == NULL) return true;
25+
if (abs(getHeight(root->left, umap) - getHeight(root->right, umap)) > 1) return false;
26+
return isBalanced(root->left) && isBalanced(root->right);
27+
}
28+
};

0 commit comments

Comments
 (0)