Postorder traversal sequence of binary search tree

Topic description

Input an integer array to determine whether the array is the result of a post-order traversal of a binary search tree.

Returns true if so, false otherwise.

Suppose any two numbers of the input array are different from each other.

Data range
Array length [0,1000].

Example
Input: [4, 8, 6, 12, 16, 14, 10]

output: true

point analysis

The thing worth absorbing in this question is whether it is a binary search tree directly based on the post-order traversal given by the question .
According to the nature of the post-order traversal of the binary search tree, the last node is obtained as the root node and saved. Then we find the first number greater than the root node from scratch, which is the first node of the right subtree of this binary search tree. In the right subtree, all points should be larger than the root. If this condition is not met, it is not a binary search tree. Then recurse down...
In the same way, we can also generalize the binary search tree based on preorder traversal

Post-order traversal judgment

class Solution {
    
    
public:
    vector<int> seq;
    
    bool verifySequenceOfBST(vector<int> sequence) {
    
    
        seq = sequence;
        int n = sequence.size();
        return dfs(0, n-1);
    }
    
    bool dfs(int l, int r) {
    
    
        if (l >= r) return true;
        
        int root = seq[r];
        int k = l;
        while (k < r && seq[k] < root) k++;
        for (int i = k; i < r; i++) 
            if (seq[i] < root) return false;
        
        return dfs(l, k-1) && dfs(k, r-1);
    }
};

preorder traversal

bool dfs(int l, int r) {
    
    
    if (l >= r) return true;
    
    int root = pre[l];
    int k = l + 1;
    while (k < r && pre[k] < root) k++;
    for (int i = k; i < r; i++)
        if (pre[i] < root) return false;
    
    return isSearch(l+1, k-1) && isSearch(k, r);
}

Guess you like

Origin http://10.200.1.11:23101/article/api/json?id=324085238&siteId=291194637