Binary search tree or not
On-Site Question 3 - SOLUTION
Problem
Given a binary tree, check whether it’s a binary search tree or not.
Requirements
Use paper/pencil, do not code this in an IDE until you've done it manually
Do not use built-in Python libraries to do this, but do mention them if you know about them
Solution
The first solution that comes to mind is, at every node check whether its value is larger than or equal to its left child and smaller than or equal to its right child (assuming equals can appear at either left or right). However, this approach is erroneous because it doesn’t check whether a node violates any condition with its grandparent or any of its ancestors.
So, we should keep track of the minimum and maximum values a node can take. And at each node we will check whether its value is between the min and max values it’s allowed to take. The root can take any value between negative infinity and positive infinity. At any node, its left child should be smaller than or equal than its own value, and similarly the right child should be larger than or equal to. So during recursion, we send the current value as the new max to our left child and send the min as it is without changing. And to the right child, we send the current value as the new min and send the max without changing.
class Node:
def __init__(self, val=None):
self.left, self.right, self.val = None, None, val INFINITY = float("infinity")
NEG_INFINITY = float("-infinity") def isBST(tree, minVal=NEG_INFINITY, maxVal=INFINITY):
if tree is None:
return True
if not minVal <= tree.val <= maxVal:
return False return isBST(tree.left, minVal, tree.val) and isBST(tree.right, tree.val, maxVal)
There’s an equally good alternative solution. If a tree is a binary search tree, then traversing the tree inorder should lead to sorted order of the values in the tree. So, we can perform an inorder traversal and check whether the node values are sorted or not.
def isBST2(tree, lastNode=[NEG_INFINITY]):
if tree is None:
return True
if not isBST2(tree.left, lastNode):
return False
if tree.val < lastNode[0]:
return False
lastNode[0]=tree.val
return isBST2(tree.right, lastNode)
This is a common interview problem, its relatively simple, but not trivial and shows that someone has a knowledge of binary search trees and tree traversals.
Good Job!
Binary search tree or not的更多相关文章
- [数据结构]——二叉树(Binary Tree)、二叉搜索树(Binary Search Tree)及其衍生算法
二叉树(Binary Tree)是最简单的树形数据结构,然而却十分精妙.其衍生出各种算法,以致于占据了数据结构的半壁江山.STL中大名顶顶的关联容器--集合(set).映射(map)便是使用二叉树实现 ...
- Leetcode 笔记 99 - Recover Binary Search Tree
题目链接:Recover Binary Search Tree | LeetCode OJ Two elements of a binary search tree (BST) are swapped ...
- Leetcode 笔记 98 - Validate Binary Search Tree
题目链接:Validate Binary Search Tree | LeetCode OJ Given a binary tree, determine if it is a valid binar ...
- Leetcode: Convert sorted list to binary search tree (No. 109)
Sept. 22, 2015 学一道算法题, 经常回顾一下. 第二次重温, 决定增加一些图片, 帮助自己记忆. 在网上找他人的资料, 不如自己动手. 把从底向上树的算法搞通俗一些. 先做一个例子: 9 ...
- [LeetCode] Closest Binary Search Tree Value II 最近的二分搜索树的值之二
Given a non-empty binary search tree and a target value, find k values in the BST that are closest t ...
- [LeetCode] Closest Binary Search Tree Value 最近的二分搜索树的值
Given a non-empty binary search tree and a target value, find the value in the BST that is closest t ...
- [LeetCode] Verify Preorder Sequence in Binary Search Tree 验证二叉搜索树的先序序列
Given an array of numbers, verify whether it is the correct preorder traversal sequence of a binary ...
- [LeetCode] Lowest Common Ancestor of a Binary Search Tree 二叉搜索树的最小共同父节点
Given a binary search tree (BST), find the lowest common ancestor (LCA) of two given nodes in the BS ...
- [LeetCode] Binary Search Tree Iterator 二叉搜索树迭代器
Implement an iterator over a binary search tree (BST). Your iterator will be initialized with the ro ...
- [LeetCode] Convert Sorted List to Binary Search Tree 将有序链表转为二叉搜索树
Given a singly linked list where elements are sorted in ascending order, convert it to a height bala ...
随机推荐
- 前端-javascript-引入
1.Javascript简介 web前端有三层: HTML:从语义的角度,描述页面的结构 CSS:从审美的角度,描述样式(美化页面) JavaScript:从交互的角度,描述行为(提升用户体验) 2. ...
- leader 选举机制
from: http://www.jasongj.com/2015/01/02/Kafka%E6%B7%B1%E5%BA%A6%E8%A7%A3%E6%9E%90/ 一种非常常用的选举leader的方 ...
- SSM总结
1 报错: cvc-complex-type.2.4.a: Invalid content was found starting with element 'async-supported'. ...
- eclipse 使用tomcat7.0建立Dynamic Web Project 时 web.xml的问题
最近使用Eclipse helios版本结合tomcat7.0建立动态的web项目时,发现在WEB-INF下的web.xml没有了. 解决方案: 建立web项目时,建到第三个下一步时,将 Genera ...
- Haskell语言学习笔记(27)Endo, Dual, Foldable
Endo Monoid newtype Endo a = Endo { appEndo :: a -> a } instance Monoid (Endo a) where mempty = E ...
- FP-growth算法高效发现频繁项集(Python代码)
FP-growth算法高效发现频繁项集(Python代码) http://blog.csdn.net/leo_xu06/article/details/51332428
- Mysql update 一个表中自己的数据
update table ucf, table t2 set ucf.pcid = t2.pcid where t2.name = 'liming' and t2.gid= ucf.gid and ...
- EnumMap实现类
从名字上看出来,EnumMap是为枚举类服务的,它的key不能为null,在创建它的时候,必须要指定一个枚举类,如: EnumMap enumMap = new EnumMap(Season.clas ...
- 可能空字符串转换为浮点型或者整数型:java.lang.NumberFormatException: For input string: " "
Integer.valueOf(str.equals("")?"0":str)
- 通过阿里OSS文件服务返回的URL获取文件流下载
我们都知道将文件上传到阿里的OSS文件服务上后,可以通过generatePresignedUrl(bucketName, key, expiration)方法获取该文件的防问路径,但是当我们知道该文件 ...