The sword refers to the post-order traversal of the binary search tree

topic link

Post sequence, left and right roots.

Let l be the left end, r be the right end, and vector a. a[r] must be the root.

Those older than a[r] are the right sons, and those smaller than a[r] are the left sons.

Then find a recursive judgment of i as the dividing line.

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

 

Guess you like

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