leetcode255 - Verify Preorder Sequence in Binary Search Tree - medium

Given an array of numbers, verify whether it is the correct preorder traversal sequence of a binary search tree.

You may assume each number in the sequence is unique.

Consider the following binary search tree: 

     5
    / \
   2   6
  / \
 1   3

Example 1:

Input: [5,2,6,1,3]
Output: false

Example 2:

Input: [5,2,1,3,6]
Output: true

Follow up:
Could you do it using only constant space complexity?

 
preorder是一路走到最左边的leaf,然后每个node访问右子树再一路回上来,再走root的右边。如果sequence里的值是逐渐变小的,说明我们在向最左leaf走。直到有个值变大了那一定是访问到某个右子树了,而它的parent一定在之前走过的node里。用一个stack装所有左子树的值,遇到比栈顶大的数x时,逐一pop stack,直到栈顶比当前这个数大,那最后一个pop出来的,也就是前一个pop出来的数就是x的parent。同时还要有一个var来track每次找到的这个parent,因为sequence里在它之后的数都应该比它大。遍历的时候每个数都要push进stack一遍,比如例子里的3,它相对于之后的6,也是5的左子树的一员。
 
实现: Time&Space O(n)
class Solution {
public:
    bool verifyPreorder(vector<int>& preorder) {
        
        stack<int> leftSubtreeValues;
        int parent = INT_MIN;
        
        for (int val : preorder){
            if (val < parent)
                return false;
            
            while (!leftSubtreeValues.empty() && leftSubtreeValues.top() < val){
                parent = leftSubtreeValues.top();
                leftSubtreeValues.pop();
            }
                
            leftSubtreeValues.push(val);
        }
            
        return true;
        
    }
};

 

posted @ 2020-10-28 12:50  little_veggie  阅读(103)  评论(0)    收藏  举报