[Cracking the Coding Interview] 4.5 Validate BST

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

猜你喜欢

转载自www.cnblogs.com/infinitycoder/p/9189521.html