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 ...
随机推荐
- spring boot 整合MongoDB
参考 https://www.cnblogs.com/nbfujx/p/7999171.html
- springboot - SqlSessionFactoryBean falls in circular dependencies by Spring Boot's DataSourceInitializer
springboot mybatis配置多数据源的时候,报错:There is a circular dependency between 7 beans in the application con ...
- 你该知道的 TValue
你该知道的 TValue Represents a lightweight version of the Variant type. TValue is a data structure that c ...
- ABAP-HTML浏览器
- Technology, globalisation and the squeeze on good jobs
Technology, globalisation and the squeeze on good jobs技术与全球化冲击好工作“Highest stock market EVER! Jobs ar ...
- Haskell语言学习笔记(25)MonadState, State, StateT
MonadState 类型类 class Monad m => MonadState s m | m -> s where get :: m s get = state (\s -> ...
- PPT地图 - 动态显示省份扩散效果
找一张中国地图矢量图,这个要找半天,自己画难度有点大.图中每个省份都是单独一张图.从我的百度云盘下载 提取码: 61ha 选中一个省份图块并复制,填充复制图块的颜色,拖拽该图块覆盖住该省份原来位置. ...
- PCA和SVD(转)
最近突然看到一个问题,PCA和SVD有什么关系?隐约记得自己照猫画虎实现的时候PCA的时候明明用到了SVD啊,但SVD(奇异值分解)和PCA的(特征值分解)貌似差得相当远,由此钻下去搜集了一些资料,把 ...
- 大型运输行业实战_day04_3_高级查询+分页
1.高级查询+分页最终结果 2.分页的本质分析 前端传入:当前页 和 每页显示条数 数据库必须查询出:数据列表 和 总共条数 页面显示包括的数据有: 列表 + 每页显示条数 + 当前页 + 总共 ...
- 关于时间查询的sql语句
今天 select * from 表名 where to_days(时间字段名) = to_days(now()); 昨天 SELECT * FROM 表名 WHERE TO_DAYS( NOW( ) ...