Verify Preorder Sequence in Binary Search Tree

来源:互联网 发布:炫光制作软件 编辑:程序博客网 时间:2024/06/05 00:17

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.

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

思路:preorder 生成的数组序列,并不像inorder那么递增,但是也还是有一定规律的,因为preorder的至少是一个BST的序列,所以,BST有性质就是:左<中<右。

也就是说,当前node的值必须比左边的要大,那么我们就维持一个stack,来保存visit当前点的左边最小值,如果后面visit出来的点值比左边还小,那就坏了return false。

说白了,就是为了验证这个树形结构是否是正确的,我们为了维护一个当前点的最小值,那么就要用stack来保存。

算法就是:只要遇见小于当前stack.peek()的点的值,就push进去,如果遇见比peek大的值,那么证明我们遇见了右边的点,那么pop stack直到peek的值比当前值大,同时我们需要更新最小值为pop的值,也就是随着我的点右移,我的最小值也应该随着往右移动,这样就模拟验证了整个tree是不是valid。注意int array也可以for循环,直接for int p就行。不需要用Integer。

public class Solution {    public boolean verifyPreorder(int[] preorder) {        if(preorder == null) return false;        int min = Integer.MIN_VALUE;        Stack<Integer> stack = new Stack<Integer>();        for(int p: preorder){            if(p < min){                return false;            }                         while(!stack.isEmpty() && stack.peek() < p){                min = stack.pop();            }            stack.push(p);        }        return true;    }}

follow up,如果需要用constant space,那就需要把最小值直接修改记录在preorder的array里面,这样就不用stack来记录历史信息。这个很巧妙。这个思想就是把array当stack用,然后把后面遇见的a,放到前面去,然后low的值取完了之后,历史信息就没有用了,所以可以把后面的值放到前面去。

public class Solution {    public boolean verifyPreorder(int[] preorder) {        if(preorder == null) return false;        int min = Integer.MIN_VALUE;        int i=-1;        for(int a: preorder){            if(a<min) return false;            while(i>=0 && a > preorder[i]){                min = preorder[i--];            }            preorder[++i] = a;        }        return true;    }}


0 0