The result of subsequent traversal of the binary search tree

question:

Input an integer array to determine whether the array is the result of a post-order traversal of a binary search tree. If yes, output Yes, otherwise output No. Suppose any two numbers of the input array are different from each other.

solve:

① In the sequence obtained by post-order traversal, the last value is the root node of the tree, and the previous numbers in the array can be divided into two parts. The first part is the value of the left subtree node, which is smaller than the root node, and the second part is the right The value of the subtree nodes, which are all greater than the value of the root node. Just find the first value greater than the root node, and then judge whether there is a number smaller than the root node in the right subtree, if so, return false; if not, recursively judge the left and right subtrees.

public class Solution {//判断是否能构成二叉搜索树
    public boolean VerifySquenceOfBST(int [] sequence) {
        if (sequence == null || sequence.length <= 0){
            return false;
        }
        return VerifySquenceOfBST(sequence,0,sequence.length - 1);
    }
    public boolean VerifySquenceOfBST(int[] sequence,int start,int end){
        if (start >= end) return true;//所有的数据都处理完成
        int i = start;
        while(i < end - 1 && sequence[i] < sequence[end]){
            i ++;
        }
        int j = i;
        while(j < end - 1 && sequence[j] > sequence[end]){
            j ++;
        }
        if (j != end - 1){
            return false;
        }
        return VerifySquenceOfBST(sequence,start,i - 1) && VerifySquenceOfBST(sequence,i,end - 1);
    }
}

Guess you like

Origin http://43.154.161.224:23101/article/api/json?id=325345650&siteId=291194637