98. 验证二叉搜索树 【中等】

题目链接

import { initTree, TreeNode } from './utils/ts-index';

// 易错解法
// function isValidBST(root: TreeNode | null): boolean {
//     if (!root) return true;
//     if(root.left?.val && root.val <= root.left?.val) return false;
//     if(root.right?.val && root.val >= root.right.val) return false;
//     return isValidBST(root.left) && isValidBST(root.right);
// };

const inOrder = (root: TreeNode|null, nodeList: number[]) => {
    if (!root) return;
    inOrder(root.left, nodeList);
    nodeList.push(root.val);
    inOrder(root.right, nodeList);
};

function isValidBST(root: TreeNode | null): boolean {
    if (!root) return true;
    let nodeList = [] as number[];
    inOrder(root, nodeList);
    let res = true;
    nodeList.forEach((it, index)=>{
        if(index+1 < nodeList.length && it >= nodeList[index+1]) res = false;
    });
    return res;
}; 

(()=> {
    const root = initTree([2,2,2]);
    console.log('isValidBST', isValidBST(root));
})();

results matching ""

    No results matching ""