255. Verify Preorder Sequence in Binary Search Tree

来源:互联网 发布:女生性格判断 知乎 编辑:程序博客网 时间:2024/06/05 08:12

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?

要验证二叉搜索树是不是合法,核心是左节点比根节点小,右节点比根节点大。这里stack只保存左树,如果当前值大于peek,说明到了一个分叉,该访问右子树,low更新为peek,下面的数都不能比这个low小,否则返回false。代码如下:

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

阅读全文
0 0
原创粉丝点击