forked from zhuli19901106/lintcode
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathbalanced-binary-tree(AC).cpp
More file actions
47 lines (45 loc) · 1.06 KB
/
balanced-binary-tree(AC).cpp
File metadata and controls
47 lines (45 loc) · 1.06 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
#include <unordered_map>
using namespace std;
/**
* Definition of TreeNode:
* class TreeNode {
* public:
* int val;
* TreeNode *left, *right;
* TreeNode(int val) {
* this->val = val;
* this->left = this->right = NULL;
* }
* }
*/
class Solution {
public:
/**
* @param root: The root of binary tree.
* @return: True if this Binary tree is Balanced, or false.
*/
bool isBalanced(TreeNode *root) {
um.clear();
if (root == NULL) {
return true;
}
um[NULL] = 0;
height(root);
return balance(root);
}
private:
unordered_map<TreeNode *, int> um;
int height(TreeNode *root) {
if (root == NULL) {
return 0;
}
return um[root] = max(height(root->left), height(root->right)) + 1;
}
bool balance(TreeNode *root) {
if (root == NULL) {
return true;
}
return balance(root->left) && balance(root->right) &&
abs(um[root->left] - um[root->right]) <= 1;
}
};