Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- #include<cstdlib>
- #include<iostream>
- using namespace std;
- class Node{
- public:
- int data;
- Node *left,*right;
- Node(int key){
- data=key;
- left=right=NULL;
- }
- };
- int IsBalanced(Node *root,int &height){
- int lh=0,rh=0;
- if(root==NULL){
- height=0;
- return 1;
- }
- int l=IsBalanced(root->left,lh);
- int r=IsBalanced(root->right,rh);
- height=max(lh,rh)+1;
- if(abs(lh-rh)>=2)
- return 0;
- return l && r;
- }
- void Insert(Node **root_ref,int key){
- if(*root_ref==NULL){
- *root_ref=new Node(key);
- return;
- }
- if((*root_ref)->data<key)
- Insert(&((*root_ref)->right),key);
- else
- if((*root_ref)->data>key)
- Insert(&((*root_ref)->left),key);
- }
- int main(){
- Node *root=NULL;
- Insert(&root,5);
- Insert(&root,7);
- Insert(&root,6);
- Insert(&root,2);
- Insert(&root,8);
- int height=0;
- if(IsBalanced(root,height))
- cout<<"yes";
- else
- cout<<"no";
- }
Add Comment
Please, Sign In to add comment