-
Notifications
You must be signed in to change notification settings - Fork 0
/
LC-BinaryTreeisBalanced.cpp
80 lines (66 loc) · 1.64 KB
/
LC-BinaryTreeisBalanced.cpp
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
#include <iostream>
using namespace std;
#include <vector>
#include <cmath>
#include <time.h>
#include <string>
#include <stack>
#include <queue>
#include <algorithm>
#include <list>
#include <set>
#include <unordered_set>
#include <map>
#include <unordered_map>
#include <bits/stdc++.h>
struct TreeNode
{
int val;
struct TreeNode* left;
struct TreeNode* right;
};
struct TreeNode* create()
{
struct TreeNode* new_node= (struct TreeNode*)malloc(sizeof(struct TreeNode));
int x;
printf("Enter data to node: ");
scanf("%d", &x);
if(x==-1)
return NULL;
new_node->val= x;
printf("Enter for Left Child of %d\n", new_node->val);
new_node->left= create();
printf("Enter for Right Child of %d\n", new_node->val);
new_node->right= create();
return new_node;
}
int subtreeDepth(TreeNode* root){
if(root==NULL) return -1;
int level= 0;
queue<struct TreeNode*> q;
q.push(root);
while(1){
int size= q.size();
if(size==0) return level-1; // depth= level-1
while(size>0){
struct TreeNode* temp= q.front();
q.pop();
if(temp->left!=NULL) q.push(temp->left);
if(temp->right!=NULL) q.push(temp->right);
size--;
}
level++;
}
return level-1;
}
bool isBalanced(TreeNode* root){
if(root==NULL) return true;
if(abs(subtreeDepth(root->left)-subtreeDepth(root->right))>1) return false;
if(isBalanced(root->left) && isBalanced(root->right)) return true;
return false;
}
int main(){
struct TreeNode* root= create();
cout<< isBalanced(root);
return 0;
}