255. Verify Preorder Sequence in Binary Search Tree

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?

二分搜索树的特点是左子树的值小于该节点,该节点小于右子树的值。本题的思路是,存储一个low值,用一个stack来存储遍历的数组值,首先遍历树的左子树,因为左子树的值都是小于cur的值,因此为了保证可以判断正确,将 low取值为Integer.MIN_VALUE;然后每次先进行一次判断,看当前的值是否大于stack的peek值,如果不大于,则说明还在左子树上面迭代,每次将其值存入stack里面。直到出现了右子树上面的点,因为其上面的点会大于其父节点,但是肯定小于父节点的父节点,因此,可以利用这一性质来确定是哪个节点的右节点。它是肯定会小于其父节点的所有父节点。代码如下:

 1 public class Solution {
 2     public boolean verifyPreorder(int[] preorder) {
 3         int low = Integer.MIN_VALUE;
 4         Stack<Integer> stack = new Stack<Integer>();
 5         for(int p:preorder){
 6             if(p<low) return false;
 7             while(!stack.isEmpty()&&p>stack.peek()){
 8                 low = stack.pop();
 9             }
10             stack.push(p);
11         }
12         return true;
13     }
14 }

follow up有一点难度,就是要求在常数的空间内完成,这里面不用stack来做,而是创建一个int来做为索引,用来记录最近的中间结点的索引值,左子树遍历的时候,是一切正常的,和上面的做法类似,而到了右子树的时候,将右子树的值和其父节点(i所在索引值)比较,如果大于,则不断循环,然后将当前值(右子树的值)存储在i的后面的位置,代码如下:

 1 public class Solution {
 2     public boolean verifyPreorder(int[] preorder) {
 3         int low = Integer.MIN_VALUE;
 4         int i=-1;
 5         for(int p:preorder){
 6             if(p<low) return false;
 7             while(i>=0&&p>preorder[i]){
 8                 low = preorder[i--];
 9             }
10             preorder[++i] = p;
11         }
12         return true;
13     }
14 }
原文地址:https://www.cnblogs.com/codeskiller/p/6603323.html