https://github.com/Premiumlab/Python-for-Algorithms--Data-Structures--and-Interviews/blob/master/Mock%20Interviews/Ride%20Share%20Start-Up%20Company/Ride%20Share%20Company%20-%20Interview%20Questions%20-%20SOLUTIONS/On-Site%20Question%203%20-%20SOLUTION.ipynb

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的更多相关文章

  1. [数据结构]——二叉树(Binary Tree)、二叉搜索树(Binary Search Tree)及其衍生算法

    二叉树(Binary Tree)是最简单的树形数据结构,然而却十分精妙.其衍生出各种算法,以致于占据了数据结构的半壁江山.STL中大名顶顶的关联容器--集合(set).映射(map)便是使用二叉树实现 ...

  2. Leetcode 笔记 99 - Recover Binary Search Tree

    题目链接:Recover Binary Search Tree | LeetCode OJ Two elements of a binary search tree (BST) are swapped ...

  3. Leetcode 笔记 98 - Validate Binary Search Tree

    题目链接:Validate Binary Search Tree | LeetCode OJ Given a binary tree, determine if it is a valid binar ...

  4. Leetcode: Convert sorted list to binary search tree (No. 109)

    Sept. 22, 2015 学一道算法题, 经常回顾一下. 第二次重温, 决定增加一些图片, 帮助自己记忆. 在网上找他人的资料, 不如自己动手. 把从底向上树的算法搞通俗一些. 先做一个例子: 9 ...

  5. [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 ...

  6. [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 ...

  7. [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 ...

  8. [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 ...

  9. [LeetCode] Binary Search Tree Iterator 二叉搜索树迭代器

    Implement an iterator over a binary search tree (BST). Your iterator will be initialized with the ro ...

  10. [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 ...

随机推荐

  1. DevExpress ImageComboBoxEdit增加

    Combo_订单类型.Properties.Items.Clear() Select Case Combo_客户名称.EditValue Case "ABC" Combo_订单类型 ...

  2. Jsch - java SFTP 文件上传下载

    使用Jsch上传.下载文件,核心步骤是:获取channel,然后使用get/put方法下载.上传文件 核心代码句: session = jSch.getSession(ftpUserName, ftp ...

  3. VB6 让程序结束后带有返回值

    第三方命令行程序运行完之后,批处理中可以随时通过errorlevel变量收取运行结果.而VB写的控制台程序却没有提供这样的功能.关于让控制台程序返回值的教程是本博客独家放出. 返回值,其实也就是进程的 ...

  4. 前端-CSS-4-伪类选择器&伪元素选择器

    1.伪类选择器(爱恨原则) -------------------------------------------------------------------------------------- ...

  5. 8 并发编程-(线程)-多线程与多进程的区别&Thread对象的其他属性或方法

    1.开启速度  在主进程下开启线程比 开启子进程快 # 1 在 主进程下开启线程 from threading import Thread def work(): print('hello') if ...

  6. 八月(The Summer is Gone)观后感

    第一次看到这部电影时觉得很亲近,黑白画面,国企改革的背景,浓浓的儿时画面感,原谅我只是一个三十不到的人,可能我比较早熟,对八九十年代还有些记忆,更早以前也通过电视.音乐.书籍等了解过一些,而那些听过又 ...

  7. VB.net 与 C# 的对应逻辑运算符

    And:对两个Boolean表达式执行逻辑和.AndAlso:与AndAlso类似,关键差异是AndAlso显示短路行为,如果AndAlso中的第一个表达式为False,则不计算第二个表达式.Or:对 ...

  8. python Count类(转)

    1.collections模块 collections模块自Python 2.4版本开始被引入,包含了dict.set.list.tuple以外的一些特殊的容器类型,分别是: OrderedDict类 ...

  9. 本地Maven库添加SQLServer2012 sqljdbc4.jar

    最近又开始搞Java项目了,学习下maven用法(ant时代真的过去了啊?) 选了个国内的小框架来做,有个小需求,客户需要用牛逼哄哄的SQLServer,新版的比如SQLServer2012的sqlj ...

  10. mysql异常

    一.Can't connect to MySQL server on 'localhost' (10061)翻译:不能连接到 localhost 上的mysql分析:这说明“localhost”计算机 ...