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. c# DbProviderFactories 多数据库支持工程模式

    DbProviderFactories.GetFactory(dbProviderName) DBProviderFactory factory = DBProviderFactorys.GetFac ...

  2. jdk下载--操作系统

    不同的操作系统需要下载不同的jdk. 查看操作系统的命令: Window系统下:>winver Linux和Unix系统下: >uname -a 根据系统不同选用不同的jdk: 下载地址: ...

  3. vector实现(只能装入string)

    #include<iostream> #include<string> #include<memory> #include<utility> using ...

  4. Mysql 知识(1)

    1. 请简洁地描述下MySQL中InnoDB支持的四种事务隔离级别名称,以及逐级之间的区别? 答: SQL标准定义的四个隔离级别为:read uncommited,read committed,rep ...

  5. How to Pronounce the Word ‘TO’

    How to Pronounce the Word ‘TO’ Share Tweet Share Tagged With: TO Reduction Study the TO reduction.   ...

  6. 判断TrueType字体

    function IsTrueTypeFont(FontName : string) : boolean;const  PITCH_MASK: byte = $0F;  var  TxMetric: ...

  7. delphi 颜色转换函数总结

    unit UColor; interface uses windows, sysutils, classes, graphics; function HexToInt(Hexa: String): L ...

  8. 吴裕雄 python神经网络 水果图片识别(2)

    import osimport numpy as npimport matplotlib.pyplot as pltfrom skimage import color,data,transform,i ...

  9. 【Linux】svn环境配置

    Ubuntu 安装svn环境配置 1. 安装 sudo apt-get install subversion 安装过程需要数据[Y] 2. svn位置选择 安装完成之后,选择svn目录位置, 将其放在 ...

  10. linux 批量删除文件名中有换行符

    ls -i | grep ^M | awk '{print $1}' | xargs -t -I [] find . -inum [] -exec rm -if {} \; 注意^M 是ctrl+v ...