Binary Search Tree: for every single node in the tree, the values in its left subtree are all smaller than its value, and the values in its right subtree are all larger than its value.
if key > root.val: root.right = self.deleteNode(root.right, key) elif key < root.val: root.left = self.deleteNode(root.left, key) else: ifnot root.left andnot root.right: returnNone elifnot root.left ornot root.right: return root.left if root.left else root.right else: # Trick Point : swap the largest number in its left subree with current node # then we recursion delete the new val in its subtree cur = root.right while cur.left: cur = cur.left root.val = cur.val root.right = self.deleteNode(root.right, cur.val) return root
# Iteration Time : O(h), Space : O(1) classSolution(object): defsearchBST(self, root, val): cur = root while cur: if cur.val == val: return cur elif cur.val < val: cur = cur.right else: cur = cur.left returnNone
Binary Search Tree actually seperate ordered list to three part, less than root.val, root.val, more than root.val instead of two part!
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15
classSolution(object): defclosestValue(self, root, target): cur = root res = cur.val while cur: if abs(cur.val - target) < abs(res - target): res = cur.val
if cur.val == target: return cur.val elif cur.val < target: cur = cur.right else: cur = cur.left return res
classSolution(object): defclosestKValues(self, root, target, k): res = [] self.dfs(root, res) # Two Pointer Shrink left, right = 0, len(res)-1 while right - left + 1 > k: if abs(res[left] - target) < abs(res[right] - target): right -= 1 else: left += 1 return res[left:right+1]
If we use Two Stack to solve PostOrder Traversal, Problem “Inorder Traversal” is more complexity than other two traversal! Whether it is or not a binary search tree, the solutions are the same!
1 push element to the stack until its left node is none
2 pop a node from the stack, traverse its right subtree
Inorder Traversal Seperated two parts!
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18
classBSTIterator(object): def__init__(self, root): cur = root self.stack = [] while cur: self.stack.append(cur) cur = cur.left
defhasNext(self): return len(self.stack) > 0
defnext(self): node = self.stack.pop() cur = node.right while cur: self.stack.append(cur) cur = cur.left return node.val