zoukankan      html  css  js  c++  java
  • 判断一个序列是不是二叉查找树的后序遍历结果

    #include <cstdlib>
    #include <iostream>
    
    using namespace std;
    //判断一个序列是不是二叉查找树的后序遍历结果
    //2013.05.22 PM
    bool isBack(int *p, int begin, int end)
    {
         //边界值判断
         if(begin>end)
         return false;
         //序列为空或者只有一个元素,不用判断,怎样都是真 
         //if(end==0 ||end==1),这个判断有问题, 
         //return true;
         if(begin==end)
         return true;
         //后序遍历最后一个元素是根 
         int root=*(p+end);
         int i=begin;
       //开始的下标,直到遇到比根大的 元素停止。 
         for(i;i!=end;++i)
         {
             if(*(p+i)>root)
             break;                          
         }
         //mid的位置是第一个比root大的元素的位置 
         int mid=i;
         //从这点开始,出现比根小的元素停止,说明不是后序的 
         for(int j=mid;j!=end;++j)
         {
                 if(*(p+j)<root)
                 return false;
         }
         //递归左边的序列 
          bool left =isBack(p,begin,mid-1);
          //递归右边的序列 
          bool right =isBack(p,mid,end-1);
          return (left&&right);
             
            
    } 
     
    
    
    int main(int argc, char *argv[])
    {
        //二叉查找树序列{1 2 3 4 5 6 7}
        //的后序排列为 1325764;
        //结果为真 
        int arr[]={1,3,2,5,7,6,4};
        //int *p=arr;
        bool res=isBack(arr,0,6);
        cout<<res<<endl;
        
        system("PAUSE");
        return EXIT_SUCCESS;
    }
  • 相关阅读:
    Expedition---POJ
    LIS的优化算法O(n log n)
    Super Jumping! Jumping! Jumping! ---HDU
    数据库连接判断
    android stuido控件
    sql查询语句
    c# 字符串操作
    windows操作
    C# sql操作
    datagridview
  • 原文地址:https://www.cnblogs.com/fickleness/p/3092783.html
Copyright © 2011-2022 走看看