leetcode.合法二叉搜索树

面试题 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
    }
};
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值