劍指Offer-Java-二叉搜索樹的後序遍歷序列

二叉搜索樹的後序遍歷序列


題目:
輸入一個整數數組,判斷該數組是不是某二叉搜索樹的後序遍歷的結果。如果是則輸出Yes,否則輸出No。假設輸入的數組的任意兩個數字都互不相同。
代碼:

package com.sjsq.test;

/**
 * @author shuijianshiqing
 * @date 2020/5/25 21:26
 */

/**
 * 輸入一個整數數組,判斷該數組是不是某二叉搜索樹的後序遍歷
 * 的結果。如果是則輸出Yes,否則輸出No。假設輸入的數組的任意
 * 兩個數字都互不相同。
 */

public class Solution {
    public boolean VerifySquenceOfBST(int [] sequence) {
        // 爲空時爲true
        if(sequence == null || sequence.length == 0){
            return false;
        }
        return helqVerifty(sequence,0,sequence.length-1);
    }

    public boolean helqVerifty(int seq[],int start,int end){
        if(start >= end){
            return true;
        }
        int key = seq[end];
        int i;
        // 找到左右子樹的分界點
        for(i = start; i < end; i++){
            if(seq[i] > key){
                break;
            }
        }
        // 判斷從右子樹有有沒有比key小的,如果有則返回false
        for(int j = i; j < end; j++){
            if(seq[j] < key){
                return false;
            }
        }
        // 判斷左子樹和右子樹是否符合
        return helqVerifty(seq,start,i-1) && helqVerifty(seq,i,end-1);
    }
}

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