[路飞]_leetcode-面试题 04.05-合法二叉搜索树

简介: leetcode-面试题 04.05-合法二叉搜索树

网络异常,图片无法展示
|


[题目地址][B站地址]


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


示例 1:


输入: 
    2
   / \
  1   3
输出: true
复制代码


示例 2:


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


解题思路


二叉搜索树的性质:


对于任意一棵子树,根节点的值大于左子节点的值,根节点的值小于右子节点的值


基于以上二叉搜索树的性质,如果对二叉搜索树进行中序遍历的话,将会得到一个严格升序的序列,


所以,我们可以对输入二叉树进行中序遍历,如果遍历过程中发现节点值违反了严格升序的性质,则说明当前二叉树不是二叉搜索树。


代码实现


var isValidBST = function(root) {
  // 前一个节点的值 是否是合法二叉搜索树标识
  let pre = null,res = true;
  // 中序遍历
  function inorder(node){
    if(node === null) return;
    inorder(node.left);
    // 如果pre为null,说明当前是第一个节点,更新pre值为当前节点值
    if(pre === null) pre = node.val
    else{
      // 如果pre小于当前节点值,更新pre
      if(pre<node.val) pre = node.val
      else{
        // 否则说明当前节点处违反了二叉搜索树的性质
        res = false;
        return;
      }
    }
    inorder(node.right);
  }
  inorder(root);
  // 返回结果
  return res;
};
复制代码


至此我们就完成了 leetcode-面试题 04.05-合法二叉搜索树


如有任何问题或建议,欢迎留言讨论!

相关文章
|
12天前
【LeetCode 45】701.二叉搜索树中的插入操作
【LeetCode 45】701.二叉搜索树中的插入操作
8 1
|
12天前
【LeetCode 44】235.二叉搜索树的最近公共祖先
【LeetCode 44】235.二叉搜索树的最近公共祖先
11 1
|
12天前
【LeetCode 48】108.将有序数组转换为二叉搜索树
【LeetCode 48】108.将有序数组转换为二叉搜索树
27 0
|
12天前
【LeetCode 47】669.修剪二叉搜索树
【LeetCode 47】669.修剪二叉搜索树
7 0
|
12天前
【LeetCode 46】450.删除二叉搜索树的节点
【LeetCode 46】450.删除二叉搜索树的节点
9 0
|
12天前
【LeetCode 42】501.二叉搜索树中的众数
【LeetCode 42】501.二叉搜索树中的众数
7 0
|
12天前
【LeetCode 41】530.二叉搜索树的最小绝对差
【LeetCode 41】530.二叉搜索树的最小绝对差
7 0
|
12天前
【LeetCode 40】98.验证二叉搜索树
【LeetCode 40】98.验证二叉搜索树
8 0
|
12天前
【LeetCode 39】700.二叉搜索树中的搜索
【LeetCode 39】700.二叉搜索树中的搜索
11 0
|
2月前
|
算法
LeetCode第96题不同的二叉搜索树
文章介绍了LeetCode第96题"不同的二叉搜索树"的解法,利用动态规划的思想和递推公式,通过计算以任意节点为根的不同二叉搜索树的数量,解决了该问题。
LeetCode第96题不同的二叉搜索树