-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathBalanced Binary Tree.cpp
More file actions
51 lines (49 loc) · 1.05 KB
/
Balanced Binary Tree.cpp
File metadata and controls
51 lines (49 loc) · 1.05 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
#include<iostream>
#include<cmath>
using namespace std;
struct TreeNode
{
int val;
TreeNode* left;
TreeNode* right;
TreeNode(int x):val(x),left(NULL),right(NULL){}
};
int depth(TreeNode* root,bool& isB){
if (root->left==NULL&&root->right==NULL)
{
return 1;
}
int llen,rlen;
if (root->left!=NULL)
llen=depth(root->left,isB);
else
llen=0;
if (root->right!=NULL)
rlen=depth(root->right,isB);
else
rlen=0;
if (abs(llen-rlen)>1)
{
isB=false;
return 0;
}
return llen>rlen?(llen+1):(rlen+1);
}
bool isBalanced(TreeNode* root) {
if (root==NULL)
return true;
bool isB=true;
depth(root,isB);
return isB;
}
int main()
{
TreeNode* root=new TreeNode(1);
root->left=new TreeNode(2);
root->right=new TreeNode(3);
root->left->left=new TreeNode(5);
bool isB;
isB=isBalanced(root);
cout<<isB;
return 0;
}