Skip to content
Open
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
77 changes: 77 additions & 0 deletions C++/BalancedTree
Original file line number Diff line number Diff line change
@@ -0,0 +1,77 @@
#include<iostream>
#include<bits/stdc++.h>
using namespace std;

class node {
public:
int data;
node* left;
node* right;

node(int d) {
this -> data = d;
this -> left = NULL;
this -> right = NULL;
}
};

node* buildTree(node* root) {

cout << "Enter the data: " << endl;
int data;
cin >> data;
root = new node(data);

if(data == -1) {
return NULL;
}

cout << "Enter data for inserting in left of " << data << endl;
root->left = buildTree(root->left);
cout << "Enter data for inserting in right of " << data << endl;
root->right = buildTree(root->right);
return root;

}

int height(node* root){
//base case
if(root==NULL){
return 0;
}
int left=height(root->left);
int right=height(root->right);
int ans=max(left,right)+1;

return ans;
}
bool isBalanced(node* root){
if(root==NULL){
return true;
}

bool left=isBalanced(root->left);
bool right=isBalanced(root->right);

bool diff=abs(height(root->left)-height(root->right)) <=1;

if(left && right && diff){
return true;
}
else{
return false;
}
}

int main() {
node* root = NULL;
//creating a Tree
root = buildTree(root);
//1 3 7 -1 -1 11 -1 -1 5 17 -1 -1 -1
cout << "Printing the height of tree : " << endl;
cout<<height(root)<<endl;

cout << "Tree is balanced or not (approach 1): " << endl;
cout<<isBalanced(root)<<endl;
return 0;
}