-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathbalanced_binary_tree.cpp
More file actions
39 lines (34 loc) · 903 Bytes
/
Copy pathbalanced_binary_tree.cpp
File metadata and controls
39 lines (34 loc) · 903 Bytes
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
/**
* 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) {
// write your code here
return maxDepth(root) != -1;
}
int maxDepth(TreeNode *node) {
if(node == NULL) {
return 0;
}
int leftDepth = maxDepth(node->left);
int rightDepth = maxDepth(node->right);
if (leftDepth == -1 || rightDepth == -1 || std::abs(leftDepth - rightDepth) > 1) {
return -1;
}
return std::max(leftDepth, rightDepth) + 1;
}
};