255. Verify Preorder Sequence in Binary Search Tree
Posted 鱼与海洋
tags:
篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了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?
/* Stack time O(n)space O(n) public class Solution { public boolean verifyPreorder(int[] preorder) { //stack preorder root -left - right 先降序后升序 Stack<Integer> stack = new Stack<>(); int min = Integer.MIN_VALUE; for(int i = 0; i < preorder.length; i ++){ if(preorder[i] < min) return false; while(!stack.isEmpty() && stack.peek() < preorder[i]){ min = stack.pop(); } stack.push(preorder[i]); } return true; } }*/ public class Solution { public boolean verifyPreorder(int[] preorder) { int i = -1; int min = Integer.MIN_VALUE; for(int num : preorder){ if(num < min) return false; while(i >= 0 && preorder[i] < num){ min = preorder[i--]; } preorder[++i] = num; } return true; } }
Follow up 参考 https://segmentfault.com/a/1190000003874375
如何验证中序序列?A:中序序列是有序的,只要验证其是否升序的就行了。
如何验证后序序列?
后序序列的顺序是left - right - root
,而先序的顺序是root - left - right
。我们同样可以用本题的方法解,不过是从数组的后面向前面遍历,因为root在后面了。而且因为从后往前看是先遇到right再遇到left,所以我们要记录的是限定的最大值,而不再是最小值,栈pop的条件也变成pop所有比当前数大得数。栈的增长方向也是从高向低了。
public static boolean verifyPostorder(int[] preorder) { int i = preorder.length; int max = Integer.MAX_VALUE; for(int j = preorder.length -1; j >=0; j--){ if(preorder[j] > max) return false; while(i < preorder.length && preorder[i] < preorder[j]){ max = preorder[i++]; } preorder[--i] = preorder[j]; } return true; }
以上是关于255. Verify Preorder Sequence in Binary Search Tree的主要内容,如果未能解决你的问题,请参考以下文章
Leetcode 255. Verify Preorder Sequence in Binary Search Tree
[LeetCode] 255. Verify Preorder Sequence in Binary Search Tree
[LeetCode] 255. Verify Preorder Sequence in Binary Search Tree 楠岃瘉浜屽弶鎼滅储鏍戠殑鍏堝簭搴忓垪
LeetCode Verify Preorder Sequence in Binary Search Tree