判斷整數序列是不是二元查找樹的後序遍歷結果(9)

第9題
判斷整數序列是不是二元查找樹的後序遍歷結果
題目:輸入一個整數數組,判斷該數組是不是某二元查找樹的後序遍歷的結果。
如果是返回true,否則返回false。

例如輸入5、7、6、9、11、10、8,由於這一整數序列是如下樹的後序遍歷結果:

         8
      /  \
     6    10
    / \  / \
   5  7 9  11
因此返回true。
如果輸入7、4、6、5,沒有哪棵樹的後序遍歷的結果是這個序列,因此返回false。

 

 

/*
  Name: 
  Copyright: 
  Author: 
  Date: 22-06-11 10:52
  Description: 判斷整數序列是不是二元查找樹的後序遍歷結果
題目:輸入一個整數數組,判斷該數組是不是某二元查找樹的中序遍歷的結果。
如果是返回true,否則返回false。
例如輸入5、7、6、9、11、10、8,由於這一整數序列是如下樹的後序遍歷結果:
      8
     / \
    6  10
   /\  /\
  5 7 9 11
因此返回true。
採用遞歸; 
如果輸入7、4、6、5,沒有哪棵樹的後序遍歷的結果是這個序列,因此返回false。
*/
#include<iostream>
#include<iomanip>
using namespace std;

bool cfun(int a[],int p,int r)
//a 爲數組,假設下標從零開始
{
    bool ret=false;
    const int len=r-p+1;
    if(p==r)
    {
    return true;
    }
    else
    {   
        bool b;
        for(int i=p;i<=r;++i)
        {
                b=true;
                for(int j=i+1;j<=r;++j)
                {
                   if(a[j]<a[i])
                   {
                      b=false;
                      break;
                   }
                }
                if(b)
                {
                     for(int j=p;j<i;++j)
                     {
                        if(a[j]>a[i])
                        {
                           b=false;
                           break;
                        }
                     }
                }
                if(b)
                {
                     if(i==p)
                     ret=cfun(a,i+1,r);
                     else
                        {
                           if(i==r)
                             ret=cfun(a,p,i-1);
                             else
                             ret=cfun(a,p,i-1)&&cfun(a,i+1,r);
                        }
                if(ret)
                return true;     
                }
                
        }
    return false;
    } 
}

int main()
{
    int a[]={7,4,6,5};
    bool b=cfun(a,0,3);
    if(b)
    cout<<"true";
    else
    cout<<"false";
    cout<<endl;
    system("pause");
    exit(0);
    }


 

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章