build bst using traversal那些题还要再看一遍
用一个stack 每次假如还在left subtree 即num 《 stack top 就push 假如大了 就一直pop知道不再大于 然后push进去
但是要记录pop出来的最后一个数字 就是已经遍历过的左子root 不能再有小于他的了 所以记录在一个int里面 每次数字都要和这个纪录比较 假如出现比他小的 就false
public class Solution {
public boolean verifyPreorder(int[] preorder) {
Stack <Integer> stack = new Stack<Integer> ();
if ( preorder == null || preorder.length == 0 )
return true;
int low = Integer.MIN_VALUE;
for ( int num : preorder ) {
if ( num < low )
return false;
while ( !stack.isEmpty() && num > stack.peek() ) {
low = stack.pop();
}
stack.push ( num );
}
return true;
}
}
验证前序遍历BST并使用栈实现

本文介绍了一种使用栈实现的算法来验证一个整数数组是否表示了一个有效的二叉搜索树(BST)的前序遍历序列。算法通过维护一个单调递增的栈来跟踪遍历过程中遇到的节点值,确保每个节点值都大于栈顶元素,从而判断序列是否符合BST的性质。
236

被折叠的 条评论
为什么被折叠?



