-
Notifications
You must be signed in to change notification settings - Fork 36
Open
Description
思路:中序遍历如果是递增的,就是搜索二叉树。
递归解法:
const isValidBST = root => {
let isValidBSTFlag = true;
let max = -Number.MAX_VALUE;
const orderSearch = root => {
if (root) {
orderSearch(root.left);
if (root.val > max) {
max = root.val;
} else {
isValidBSTFlag = false;
}
orderSearch(root.right);
}
}
orderSearch(root);
return isValidBSTFlag;
};
非递归解法:
const isValidBST = root => {
if(!root) return true;
let stack = [];
let isValidBSTFlag = true;
let max = -Number.MAX_VALUE;
while (1) {
while(root != null){
stack.push(root);
root = root.left;
}
if (stack.length === 0) break;
let node = stack.pop();
if (node.val > max) {
max = node.val;
} else {
isValidBSTFlag = false;
break;
}
root = node.right;
}
return isValidBSTFlag;
}
Reactions are currently unavailable