判断二叉排序树的后序遍历是否合法

来源:互联网 发布:有什么网络兼职可以做 编辑:程序博客网 时间:2024/05/17 22:24

思想:通过根节点将序列划分为左子树序列和右子树序列,他们必须满足的条件是:左子树序列中的所有值小于根节点,右子树中所有值大于根节点,然后递归判断左子树序列和右子树序列

#include<iostream>
using namespace std;


bool VerifySquenceOfBST(int sequence[],  int length)
{
     if (sequence  ==  NULL  ||  length  <=0)
         return   false ;
     int   root  =  sequence[length  -1];
     //在二叉搜索树中左子树的结点小于根结点
    int   i = 0;
    for(;  i  <  length  -1;++  i )
    {
        if ( sequence [ i ]>  root )
            // break ;
        {
           break;
            return   false ;
        }
    }
     //在二叉搜索树中右子树的结点大于根结点
     int j = i;
     for(;j < length - 1;++j)
    {
         if (sequence[j] < root)
         {
             break;
            return   false ;
         }
    }
     //判断左子树是不是二叉搜索树
     bool left = true ;
     if(i > 0)
         left = VerifySquenceOfBST(sequence,i);
     //判断右子树是不是二叉搜索树
     bool right = true ;
     if (i < length - 1)
         right = VerifySquenceOfBST(sequence + i ,length - i -1);
     return(left && right);
}


int main()
{
    int sequence[] = {4,8,6,12,16,14,10};
    if(VerifySquenceOfBST(sequence,7))
    {
        cout<<"nimei"<<endl;
    }
    else
    {
        cout<<"daf"<<endl;
    }
    return 0;
}

0 0
原创粉丝点击