验证前序遍历的二叉树是否是 BST
- Runtime: 84 ms, faster than 64.71%
- Memory Usage: 43.4 MB, less than 17.65%
- 时间复杂度O(n),空间复杂度O(n)
维护一个栈用来获取每次的根节点,遍历比较左,弹出用来比较右边
/**
* @param {number[]} preorder
* @return {boolean}
*/
var verifyPreorder = function(preorder) {
let root = Number.MIN_SAFE_INTEGER;
const stack = [];
for (let item of preorder) {
if (item < root) {
return false;
}
let len = stack.length;
while (len > 0 && stack[len - 1] < item) {
root = stack.pop();
len = stack.length;
}
stack.push(item);
}
return true;
};
网友评论