Leetcode255-验证前序遍历序列二叉搜索树
作者:互联网
class Solution {
public boolean verifyPreorder(int[] preorder) {
LinkedList<Integer> stack=new LinkedList<>();
int preElem=Integer.MIN_VALUE;
for(int i=0;i<preorder.length;i++){
//右子树元素必须要大于递减栈被peek访问的元素,否则就不是二叉搜索树
if(preorder[i]<preElem){
return false;
}
while(!stack.isEmpty() && stack.peek()<preorder[i]){
//数组元素大于单调栈的元素了,表示往右子树走了,记录下上个根节点
preElem=stack.removeFirst();
}
stack.addFirst(preorder[i]);
}
return true;
}
}
标签:preorder,LinkedList,Leetcode255,前序,二叉,int,preElem 来源: https://www.cnblogs.com/fao99/p/16198521.html