阅读说明: 保留原笔记的编号与章节顺序;代码只供查看,没有在本站运行。历史输出不代表当前版本的复现结果。截图/外链图以独立整理的公式、表格、示意或文字替换;纠错与必要补充均作说明。
1. Definition
- All keys in the left subtree of a node are lesser than the node’s key
- All keys in the right subtree of a node are greater than the node’s key
- The left and right subtree each must also be a binary search tree
Inorder traversal outputs nodes in increasing order
2. BST as a data structure
2.1 Basic structure
class BstNode:
def __init__(self, key, value):
self.key = key
self.value = value
self.left = None
self.right = None- Key: unique identifier
- Value: the actual data
Given a key, people can retrieve the value associated with the key. If the problem is simple, key and value can be combined into one.
2.2 Comparison
| Search | Insert | Delete | |
|---|---|---|---|
| BST | O(Height) | O(Height) | O(Height) |
| Array | O(n) | ||
| O(logN) for ordered | O(n) | O(n) | |
| LinkedList | O(n) | O(n)Search + O(1)Insert | O(n)Search + O(1)Insert |
| Hash Table(Dict) | O(1) | O(1) | O(1) |
BST advantages over hash table:
- Get all keys in sorted order by just doing inorder traversal of BST. This is not a natural operation in Hash Tables.
- Range query/closest lower or greater are easy with BSTs.
- BSTs are easy to implement compared to hashing. For Hashing, we generally rely one libraries provided by programming languages.
- With self-balanced BSTs, all operations are guaranteed to work in O(logN) time. But with Hashing, O(1) is average time and some particular operations may be costly, especially when table resizing happens.
3. Operation
class BstNode:
def __init__(self, value):
self.value = value
self.val = value # 兼容下方验证算法的节点字段
self.left = None
self.right = None3.1 BST traversal
Validate whether a given binary tree is a binary search tree or not?
3.1.1 Inorder
BST => Inorder is increasing order
Inorder is increasing order => BST
def inorder(root, prev):
if not root:
return True
if not inorder(root.left, prev):
return False
if prev[0] >= root.val:
return False
prev[0] = root.val
if not inorder(root.right, prev):
return False
return True
def isValidBST(root):
prev = [-float('inf')] # 传参
return inorder(root, prev)3.1.2 Preorder
BST边界: 根10取(-∞,+∞),左5取(-∞,10),右14取(10,+∞);左5的右7只允许(5,10)。每条边继承祖先限制,而不只是比较当前父子。
-
How to Narrow min/max?
- Root is the upper limit of the left node.
- Root is the lower limit of the right node.
-
How to check if BST? Current node in (mini, maxi)
def isBST(node):
return isBSTUtil(node, -float('inf'), float('inf'))
def isBSTUtil(node, mini, maxi):
if node is None:
return True
if not (mini < node.val < maxi):
return False
return isBSTUtil(node.left, mini, node.val) and isBSTUtil(node.right, node.val, maxi)3.1.3 Postorder/bottom up
判断小范围,返回大范围
自底向上三元组: 返回(是否BST, 子树最小值, 子树最大值)。当前节点需大于左最大、小于右最小;返回的极值来自非空子树。缺失用None,不能把数值0当作缺失。
def impl(root):
if not root:
return True, None, None
boolean1, min1, max1 = impl(root.left)
boolean2, min2, max2 = impl(root.right)
boolean = boolean1 and boolean2 \
and (max1 is None or max1 < root.val) and (min2 is None or root.val < min2)
return boolean, min1 if min1 is not None else root.val, max2 if max2 is not None else root.val
class Solution(object):
def isValidBST(self, root):
return impl(root)[0]3.2 Query(Search), Insert and Delete
3.2.1 Query
-
Case 1: root.key == key, return the node’s value.
-
Case 2: root.key > key, we should look the key again inside left subtree.
-
Case 3: Otherwise, we should do the lookup in right subtree.
-
Recursion
class Node(object):
def __init__(self, key, value):
self.key = key
self.value = value
self.left = self.right = None
class BinarySearchTree(object):
def __init__(self):
self.__root = None
def __query(self, root, key):
if not root or key == root.key:
return root
if key < root.key:
return self.__query(root.left, key)
elif key > root.key:
return self.__query(root.right, key)
def query(self, key):
return self.__query(self.__root, key)- Iteration
class BinarySearchTree(object):
def __init__(self):
self.__root = None
def query(self, key):
curr = self.__root
while curr and curr.key != key:
if key < curr.key:
curr = curr.left
elif key > curr.key:
curr = curr.right
return currTail Recursion:
A tail recursion is a recursive function where the function calls itself at the end (“tail”) of the function in which no computation is done after the return of the recursive call.
Tail Recursion can always be translated to iterative calls.
3.2.2 Insert
Key: Insert as leaf!
插入: 沿小于走左、大于走右,直到空位置创建叶;已有key的处理要有明确约定。本例相等时保留原节点,不新增重复键。
class BinarySearchTree(object):
def __insert(self, root, key):
if not root:
return Node(key, key)
if key < root.key:
root.left = self.__insert(root.left, key)
elif key > root.key:
root.right = self.__insert(root.right, key)
return root
def insert(self, key):
self.__root = self.__insert(self.__root, key)整理注: 本节多个BinarySearchTree定义是分段方法示例,不是逐段覆盖后就自动得到的完整类;组合使用时保留__init__与Node定义。
3.2.1 Delete
- Case 1: The node to be deleted has no children
删除六个示意归为四类: 无子节点直接移除;仅右孩子用右孩子替代;仅左孩子用左孩子替代;有两个孩子时用右子树最小后继替代。若右孩子没有左孩子,它就是后继;否则沿右子树left链摘下最小节点,并把它原右孩子接回原父节点,再接原左右子树。
-
Case 2: has no left child
-
Case 3: has nor right child
-
Case 4: has both left and right children.
We need to move some nodes form the left/right subtree to replace it.-
Case 4.1: node.right does not have left child, meaning itself is the smallest node. In this case, we just move 8.right up. (8.right没有左孩子,8.right直接代替8)
-
Case 4.2: node.right has a left child, we need to find the smallest node and move it up.
-
class BinarySearchTree(object):
def __delete(self, root, key):
if not root:
return None
if key < root.key:
root.left = self.__delete(root.left, key)
return root
elif key > root.key:
root.right = self.__delete(root.right, key)
return root
else:
# case 1,2
if not root.left:
return root.right
# case 3
if not root.right:
return root.left
# case 4.1
if root.right.left is None:
root.right.left = root.left
return root.right
# case 4.2
# Step1. Find and delete smallest node in root.right
smallest = self.__findAnddeleteMin(root.right)
# Step2. Connect the smallest node with the root.left and root.right
smallest.left = root.left
smallest.right = root.right
return smallest
def delete(self, key):
self.__root = self.__delete(self.__root, key)
def __findAnddeleteMin(self, root):
# 最小的孩子没有左孩子
prev = root
cur = root.left
while cur.left is not None:
prev = cur
cur = cur.left
prev.left = prev.left.right
return cur4. Questions
4.1 Range Sum of BST
Given the root node of a BST, return the sum of values of all nodes with value between L and R (inclusive). The BST is guaranteed to have unique values.
class Solution(object):
def rangeSumBST(self, root, L, R):
if root is None:
return 0
if root.val < L:
return self.rangeSumBST(root.right, L, R)
elif root.val > R:
return self.rangeSumBST(root.left, L, R)
else:
return self.rangeSumBST(root.left, L, root.val) + root.val \
+ self.rangeSumBST(root.right, root.val, R)范围查询剪枝: node<L时左侧全部过小,只查右侧;node>R时只查左侧;在[L,R]内则计入当前并查两侧。最坏所有节点都落在范围内,时间O(n)。
4.2 Sorted Array to BST
Given an array where elements are sorted in ascending order, convert it to a height balanced BST.
For testing purpose, please make sure for any node in the result, its left sub-tree should have equal or only one more node than its right sub-tree.
升序数组构树: [1,3,4,5,8,11]取上中位数5作根,左子树由[1,3,4]构造、右子树由[8,11]构造;这样左侧节点数等于或只多一个。
class Solution(object):
def sortedArrayToBST(self, nums):
if len(nums) == 0:
return None
return self.helper(nums, 0, len(nums) - 1)
def helper(self, nums, left, right):
if left > right:
return None
mid = (left + right + 1) // 2 # 要+1,因为For testing purpose
node = TreeNode(nums[mid])
node.left = self.helper(nums, left, mid - 1)
node.right = self.helper(nums, mid + 1, right)
return node4.2 Trim BST
Given a root node of binary search tree, a lower bound and an upper bound, remove nodes that are outside of [lower, upper]. Return the root node after trimming the binary search tree. The root returned may not the same as the given root node. Return root as null if entire tree has been trimmed.
裁剪: 原BST层序[5,2,8,1,3,6,9]限定[2,4]后,根5被剔除并转向左子树;1低于下界被剔除,保留2(right=3)。
class Solution(object):
def trimBST(self, root, lower, upper):
if root is None:
return None
if root.val < lower:
return self.trimBST(root.right, lower, upper)
if root.val > upper:
return self.trimBST(root.left, lower, upper)
root.left = self.trimBST(root.left, lower, upper)
root.right = self.trimBST(root.right, lower, upper)
return root