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 ...
随机推荐
- kubernet使用笔记
centos7.3下安装及部署:http://www.linuxidc.com/Linux/2017-02/140723.htm
- hbase表的多版本读写
TTL(Time To Live)生存期 hbase表默认保存一个版本的数据 hbase(main):123:0> create 't_name','st1'Created table t_na ...
- delphi 加密 XOR
From http://www.delphigeist.com/2009/09/text-encryption-with-xor.html Text encryption with XOR Ev ...
- discuz 修改积分策略( 在周期中添加"每周" )
在 source/admincp/admincp_credits.php 文件中, ctrl+f 搜索 $lang['setting_credits_policy_cycletype_1'] 处, ...
- C# 窗口页面卡的处理方案-异步编程委托
今天用winform做了一个小程序,主要是用于远程数据的登录采集,因为数据量非常大,到时每次点击按钮执行程序的时候界面都会出现假死状态,具体表现是无法拖动窗口,无法最小化或关闭等,只能任务管理进程结束 ...
- 用R包来下载sra数据
1)介绍 我们用SRAdb library来对SRA数据进行处理. SRAdb 可以更方便更快的接入 metadata associated with submission, 包括study, sa ...
- CentOS6.5下安装ActiveMQ
1.下载ActiveMQ [root@localhost softwares]# wget http://archive.apache.org/dist/activemq/apache-activem ...
- Cause: org.xml.sax.SAXParseException; lineNumber: 45; columnNumber: 62; 元素内容必须由格式正确的字符数据或标记组成。
三月 09, 2018 12:13:39 下午 org.apache.catalina.core.StandardContext listenerStart严重: Exception sending ...
- python webdriver启动IE浏览器
from selenium import webdriverfrom selenium.webdriver.common.desired_capabilities import DesiredCapa ...
- malloc、free、new、delete
一.C语言中不定大小多维数组的处理: 如果要给二维数组(m*n)分配空间,代码可以写成下面: char **a, i; // 先分配m个指针单元,注意是指针单元 // 所以每个单元的大小是sizeof ...