[路飞]_合法二叉搜索树

194 阅读1分钟

面试题 04.05. 合法二叉搜索树

题目

实现一个函数,检查一棵二叉树是否为二叉搜索树。

示例1

输入: 
    2
   / \
  1   3
输出: true

示例2

输入:
    5
   / \
  1   4
     / \
    3   6
输出: false
解释: 输入为: [5,1,4,null,null,3,6]。
     根节点的值为 5 ,但是其右子节点值为 4

题解

中序遍历

二叉搜索树中序遍历得到的一定是递增数组
用数组result中序遍历二叉树数据
枚举resukt数据,如果result不是严格递增数列返回false否则返回true

代码

var isValidBST = function(root) {
    if(root === null) return true;
    let result = []
    helper(root)
    if(result.length === 1) return true;
    let min = result[0]
    for(let i = 1 ; i <result.length ; i++){
        if(min >= result[i]) return false
        min = result[i]

    }
    return true
    function helper(node){
        if(node === null) return;
        helper(node.left)
        result.push(node.val)
        helper(node.right)
        
    }
};

上述代码用到了递归还用了一个额外数组保存数据,感觉可以优化一下,删除数组

代码如下

代码

var isValidBST = function(root) {
    if(root === null) return true;
    let max = -Infinity
    return helper(root)
    function helper(node){
        if(node === null) return true;
        if(helper(node.left)){
            if(max < node.val){
                max = node.val;
                return helper(node.right)
            }
        }
        return false
    }
};