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 ...
随机推荐
- UCenter 的目录结构
以下关于文件的阐述以及代码的样例,均以 PHP 程序为例. UCenter 的目录结构 UCenter 分为服务端和客户端 2 个部分.服务端目录为“upload/”,客户端目录为“client/ ...
- 2.登录linun 输入密码登录不进去 进入单用户模式 修改 然后reboot
centos进入单用户模式 单用户模式,就是你现在站在这台机器面前能干的活,再通俗点就是你能够接触到这个物理设备. 一般干这个活的话,基本上是系统出现严重故障或者其他的root密码忘记等等,单用户模式 ...
- 机器学习入门-数据下采样 np.random_choice
1. np.random_choice(array, len) 进行随机的数据选择,array表示抽取的对象,len表示抽取样本的个数 数据的下采样是对多的数据进行np.random.choice ...
- ServiceLoader实现原理
在java中根据一个子类获取其父类或接口信息非常方便,但是根据一个接口获取该接口的所有实现类却没那么容易. 有一种比较笨的办法就是扫描classpath所有的class与jar包中的class,然后用 ...
- Java中static代码块,{}大括号代码块,构造方法代码块执行顺序!
注:下列代码中的注释都是JUnit4单元测试运行结果. 首先,没有父类的(父类是Object)的类A package Static.of; public class A { { System.out. ...
- javascript中的二维数组
要创建一个二位数组我们脑子里第一个出现的就是 var arr=[][]; 但是在javascript这样是会报错的,要在javascrip中创建一个二位数组对象方法如下 方法一 直接把数组写出 ...
- Hadoop 集群的一些问题
1.创建用户hadoop adduser hadoop passwd hadoop usermod -a -G hadoop hadoop chown -R hadoop:hadoop /data ...
- Linux终极渗透测试命令总结
本文主要和大家分享Linux终极渗透测试命令总结,如下是一份 Linux 机器的渗透测试备忘录,是在后期开发期间或者执行命令注入等操作时的一些典型命令,设计为测试人员进行本地枚举检查之用. 命令 描述 ...
- maven部署项目流程(区分环境)
java项目区分环境打包部署到Linux 本文以一个简单的HelloWorld的项目为例,从pom.xml配置到打jar包,最后在linux上运行并验证来对maven部署的这套流程进行简单介绍. 为方 ...
- 真机IOS8.3以上的文件夹共享
ios8.3以上的版本,苹果规定需要验证身份,将不在默认开启文件共享,但是在实际测试工作中,提取文件是经常需要做的操作,笔者在使用GT采集性能数据后,通过itoos或itunes都无法获得目标app的 ...