Pre-order to post-order traversal

后端 未结 11 1498
挽巷
挽巷 2020-12-23 21:56

If the pre-order traversal of a binary search tree is 6, 2, 1, 4, 3, 7, 10, 9, 11, how to get the post-order traversal?

11条回答
  •  甜味超标
    2020-12-23 22:37

    Here pre-order traversal of a binary search tree is given in array. So the 1st element of pre-order array will root of BST.We will find the left part of BST and right part of BST.All the element in pre-order array is lesser than root will be left node and All the element in pre-order array is greater then root will be right node.

    #include 
    using namespace std;
    int arr[1002];
    int no_ans = 0;
    int n = 1000;
    int ans[1002] ;
    int k = 0;
    
    int find_ind(int l,int r,int x){
        int index = -1; 
        for(int i = l;i<=r;i++){
            if(x x){
                no_ans = 1;
                return index;
            }
        }
        for(int i = index;i<=r;i++){
            if(arr[i]= n || l >r ) return;
        ans[k++] = arr[l];
        if(l==r) return;
        int index = find_ind(l+1,r,arr[l]);
        if(no_ans){
            return;
        }
        if(index!=-1){
            postorder(index,r);
            postorder(l+1,index-1);
        }
        else{
            postorder(l+1,r);
        }
    }
    
    int main(void){
    
        int t;
        scanf("%d",&t);
        while(t--){
            no_ans = 0;
            int n ;
            scanf("%d",&n);
    
            for(int i = 0;i>arr[i];
            }
            postorder(0,n-1);
            if(no_ans){
                cout<<"NO"<=0;i--){
                    cout<

提交回复
热议问题