首页 > 其他 > 详细

[Cracking the Coding Interview] 4.5 Validate BST

时间:2018-06-16 10:03:50      阅读:178      评论:0      收藏:0      [点我收藏+]

Implement a function to check if a binary tree is a binary search tree.

 

这道题很经典,让我们判断一棵树是不是二叉查找树。但是首先要确定一下二叉查找树的定义,比如leetcode 98题中的定义左<根<右就可以直接通过判断中序遍历是不是有序序列就可以了。但是一般的BST定义的是左<=根<右,就不可以用这种方法来判断。

如果是如上定义,直接根据定义递归的检查下每一个node是否满足定义就可以了,如下:

(对于root来说给定最大值为Integer.max,最小值为Integer.min,然后递归判断左子树的根节点,最小值是Integer.min, 最大值时根节点的值,以此递归)

def is_valid_bst(root)
  return helper(root, 1 << 32, -(1 << 32))
end

def helper(root, max, min)
  return true unless root
  return false if root.val >= max || root.val <= min
  
  return helper(root.left, root.val, min) && helper(root.right, max, root.val)
end

 

[Cracking the Coding Interview] 4.5 Validate BST

原文:https://www.cnblogs.com/infinitycoder/p/9189521.html

(0)
(0)
   
举报
评论 一句话评论(0
关于我们 - 联系我们 - 留言反馈 - 联系我们:wmxa8@hotmail.com
© 2014 bubuko.com 版权所有
打开技术之扣,分享程序人生!