Abstract
- Also known as BST
- Nodes have a value attached to it. If the left sub-tree isn’t empty, all nodes on that sub-tree is smaller than the value of Root Node. If the right sub-tree isn’t empty, all nodes on that sub-tree is bigger than the root node value. Its left sub-tree and right sub-tree are also binary search tree
Access previous node from current node
Use a variable
prevNode
to keep track of the previous node. Handy in solving some problems.
Practice questions
BST Node Traversal
- We can use In-Order Traversal to print the nodes inside a BST from smallest to the biggest or from biggest to smallest with
From smallest to the biggest
Go to the left subtree then right subtree. Useful in finding the minimum absolute difference among the nodes
From biggest to the smallest
Go to the right subtree then left subtree. Useful in converting the BST to Greater Tree.
BST Node Search
Attention
We can only achieve if the BST is Height-Balanced. A not height-balanced BST can be degraded into a Degenerate Binary Tree.
- If the current node isn’t the node we are finding, select the
node.left
when target value is smaller than the current node, otherwise selectnode.right
- This allows us to choose only one side of the Binary Search Tree (二叉搜索树) at each Level, achieving speed
Practice questions
BST Node Insertion
Attention
We can only achieve if the BST is Height-Balanced. A not height-balanced BST can be degraded into a Degenerate Binary Tree.
- The idea is to insert the new node as a Leaf Node to minimise modification to the Binary Search Tree (二叉搜索树)
- The suitable
null
slot can be found in speed by going down the BST using the BST Node Search
Practice questions
BST Node Deletion
- When the Degree of the deleted node is , we can just remove it without any other modifications
- When the Degree of the deleted node is , we can just need to smallest node from its right subtree without any other modifications
- When the Degree of the deleted node is , we can just need to replace it with smallest node from its right subtree or the biggest node from its left subtree. Below shows replacing the deleted node with the smallest node from its right subtree
- We can encapsulate the logic of BST node deletion in the three situations described above into a single
remove()
function
Practice questions
Leetcode Question
Properties
Modification & Structure
Common Ancestor
Terminologies
Greater Tree
- Every value of node of the original BST is changed to the original value of node plus the sum of all value of nodes greater than the value of the original node of in BST
Practice questions