Post-order traversal sequence of binary search tree

Topic source: Niuke.com

programming connection

Topic description

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.

Parse:

Taking into account the characteristics of subsequent traversal, the last arity is the root node. The
first few will be smaller than the root node, which is the left subtree
. The last few will be larger than the root node, which is the right subtree
. Both recursive and non-recursive can be used.

Recursive code:

class Solution {
public:
    bool VerifySquenceOfBST(vector<int> sequence) {
        return sequence.size()==0? false:SquenceOfBST(sequence,0,sequence.size());
    }

   bool SquenceOfBST(vector<int> &sequence, int l, int r)
    {
        if (l == r)
            return true;
        int mid = l, last = 0;
        for (; mid < r - 1 && sequence[mid] < sequence[r - 1]; ++mid);
        for (last = mid; last < r - 1 && sequence[last] > sequence[r - 1]; ++last);
        return last == r - 1 && SquenceOfBST(sequence, l, mid) && SquenceOfBST(sequence, mid, r - 1);
    }
};

Non-recursive:

class Solution {
public:
    bool VerifySquenceOfBST(vector<int> sequence) {
        if (sequence.size() == 0)
            return false;
        int last = sequence.size() - 1;
        for (int i = 0; last != 0; last--, i = 0) {
            for (; sequence[i] < sequence[last]; ++i);
            for (; sequence[i] > sequence[last]; ++i);
            if (i != last)
                return false;
        }
        return true;
    }
};

Guess you like

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