js(74)~面试题 04.05. 合法二叉搜索树

83 阅读1分钟

力扣本题传送门

这道题,考二叉搜索树概念,左《 根 《 右节点,这个跟中序遍历左根右跟着二叉搜索树的大小顺序一样,所以配合中序遍历是一个思路,

但是中序遍历我并不熟悉,所以贴上代码做个对比

var isValidBST = function(root) {
    let stack = [];
    let inorder = -Infinity;

    while (stack.length || root !== null) {
        while (root !== null) {
            stack.push(root);
            root = root.left;
        }
        root = stack.pop();
        // 如果中序遍历得到的节点的值小于等于前一个 inorder,说明不是二叉搜索树
        if (root.val <= inorder) {
            return false;
        }
        inorder = root.val;
        root = root.right;
    }
    return true;
};

题外话二叉树中序遍历

var inorderTraversal = function(root) {
    const res = [];
    const stk = [];
    while (root || stk.length) {
        while (root) {
            stk.push(root);
            root = root.left;
        }
        root = stk.pop();
        res.push(root.val);
        root = root.right;
    }
    return res;
};