【6】判斷整數序列是否是二元查找樹的後序遍歷結果

/*************************************************ios

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

例如輸入五、七、六、九、十一、十、8,因爲這一整數序列是以下樹的後序遍歷結果:spa

         8
        /  \
     6    10
    / \     / \
   5  7 9  11
所以返回true。
若是輸入七、四、六、5,沒有哪棵樹的後序遍歷的結果是這個序列,所以返回false。code

/*************************************************排序

二叉排序樹(Binary S ort Tree)或二叉查找樹(Binary Search Tree)或者是一棵空樹,或者是具備下列性質的二叉樹:io

(1)若左子樹不空,則左子樹上全部結點的值均小於它的根結點的值;class

(2)若右子樹不空,則右子樹上全部結點的值均大於它的根結點的值;stream

(3)左、右子樹也分別爲二叉排序樹;二叉樹

(4)沒有鍵值相等的結點。遍歷

後序遍歷:左右根

分析:

一、後序遍歷的最後一個節點是根節點;

#include <iostream>
using namespace std;

/*
typedef struct BSTreeNode{
    int data;
    BSTreeNode *left;
    BSTreeNode *right;
}BSTreeNode,*BSTree;
*/
//判斷給定序列是不是排序二叉樹的後序遍歷輸出

int is_backsort(int *a,int start,int end){
    if(start>=end){
        return 0;
    }
    int root=a[end];
    int i=start;
    int j=end-1;
    if(i<j){
        while(a[i]<root && i<j){
            i++;
        }
        while(a[j]>root && i<j){
            j--;
        }
    }
    //cout<<"i:"<<i<<a[i]<<"j:"<<j<<a[j]<<endl;
    if(i<j){
        return -1;
    }
    is_backsort(a,start,i-1);
    is_backsort(a,i+1,end);
    return 0;
}

int main(){
    int a[]={5,7,6,9,11,10,8};
    for(int i=0;i<=6;i++){
        cout<<a[i]<<" ";
    }
    
    cout<<endl;
    int ret=is_backsort(a,0,6);
    cout<<"ret:"<<ret<<endl;
    
}
相關文章
相關標籤/搜索