110.平衡二叉树

110.平衡二叉树_第1张图片

#include  
#include
using namespace std;
struct TreeNode {
      int val;
      TreeNode *left;
      TreeNode *right;
      TreeNode(int x) : val(x), left(0), right(0) {}
  };
  struct BinNode {
      int val;
      int height;
      BinNode* left;
      BinNode* right;
      BinNode* parent;
      BinNode(int x) : val(x), left(0), right(0),height(0),parent(0) {}
  };
void fun1(TreeNode* root1,BinNode* root2);
void fun2(BinNode*t);
bool fun3(BinNode*x);
//TreeNode树变BinNode树
void fun1(TreeNode* root1,BinNode* root2) {
    stack<TreeNode*> s1; 
    stack<BinNode*> s2; 
    if (root1) { s1.push(root1); s2.push(root2); }
    while (!s1.empty()) { 
        root1 = s1.top(); 
        root2 = s2.top();
        s1.pop();
        s2.pop();
        root2->val = root1->val;//复制
        if (root1->right != 0) { 
            s1.push(root1->right); 
            root2->right = new BinNode(0);
            root2->right->parent=root2;
            fun2(root2->right);
            s2.push(root2->right);
        }
        if (root1->left != 0) { 
            s1.push(root1->left); 
            root2->left = new BinNode(0);
            root2->left->parent=root2;
            fun2(root2->left);
            s2.push(root2->left);
        }
    }
}
//更新历代祖先高度
void fun2(BinNode*t){
    int l;
    int r;
    while (t->parent!=0)
    {   
        //如果t的兄弟为空
    if(t->parent->left==0) {l=-1;}
    else
    {
        l=t->parent->left->height;
    }
    if(t->parent->right==0) {r=-1;}
    else
    {
        r=t->parent->right->height;
    }
    
    if(t->parent->right==0) r=0;
        int old=t->parent->height;
        t->parent->height=max(l,r)+1;//更新高度
        if(old==t->parent->height){return;}//高度没变
        t=t->parent;
    }    
}
//遍历监测
bool fun3(BinNode*x){
stack<BinNode*> s; //辅助栈
   if ( x ) s.push ( x ); //根节点入栈
   while ( !s.empty() ) { //在栈变空之前反复循环
      x = s.top(); //弹出并访问当前节点,其非空孩子的入栈次序为先右后左
      //判断平衡否
      if(x->left==0){
          
          if(x->right!=0&&x->right->height>0) return false;
      }
      if(x->right==0){
          if(x->left!=0&&x->left->height>0) return false;
      }
      if(x->left!=0&&x->right!=0&&(x->left->height-x->right->height<-1||x->left->height-x->right->height>1)) return false;
      s.pop();
      if ( x->right!=0 ) s.push ( x->right ); 
	  if ( x->left!=0 ) s.push ( x->left );
   }
   return true;

}


    bool isBalanced(TreeNode* root) {
    BinNode*p=new BinNode(0);
    fun1(root,p);
    return fun3(p);    
    }
int main(){
    TreeNode* p=new TreeNode(1);
    TreeNode* p2=new TreeNode(2);
    TreeNode* p3=new TreeNode(3);
    TreeNode* p4=new TreeNode(4);
    TreeNode* p5=new TreeNode(5);
    p->right=p2;
    p->left=p4;
    p2->right=p3;
    p2->left=p5;
    cout<< isBalanced(p)<<endl;
    return 0;
}

你可能感兴趣的:(数据结构与算法)