71 lines
1.7 KiB
JavaScript
Raw Permalink Blame History

This file contains ambiguous Unicode characters

This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.

/**
* Definition for a binary tree node.
* function TreeNode(val, left, right) {
* this.val = (val===undefined ? 0 : val)
* this.left = (left===undefined ? null : left)
* this.right = (right===undefined ? null : right)
* }
*/
/**
* @param {TreeNode} root
* @return {boolean}
*/
const isValidBST = function (root) {
};
/*
思路根据二叉搜索树的定义BST的中序遍历是一个严格的递增序列所以只要一次遍历判断后一个树是否是严格大于当前的树如果小于等于
那么这个二叉树不是搜索二叉树
*/
function f1(root) {
let prev = null; // 前一个节点的值
const inordertraversal = (node) => {
if (!node) return true; // 空节点被视为有效BST
// 遍历左子树如果左子树不是BST立即返回false
if (!inordertraversal(node.left)) return false;
// 处理当前节点
if (prev !== null && prev >= node.val) return false;
// 更新prev为当前节点值
prev = node.val;
// 遍历右子树
return inordertraversal(node.right);
};
return inordertraversal(root);
}
/*
使用迭代法中序遍历,返回更直接
*/
function f2(root) {
const stack = [];
let prev = null;
// 迭代法中序遍历
while (stack.length > 0 || root !== null) {
// 遍历左子树,直到最左叶子节点
while (root !== null) {
stack.push(root);
root = root.left;
}
// 访问当前节点
root = stack.pop();
// 当前节点值必须大于前一个节点值
if (prev !== null && root.val <= prev) {
return false; // 发现不符合要求返回false
}
// 更新prev为当前节点值
prev = root.val;
// 访问右子树
root = root.right;
}
return true;
}