A Binary Search Tree is a special form of a binary tree. The value in each node must be greater than (or equal to) any values in its left subtree but less than (or equal to) any values in its right subtree.
二叉查找树的基本操作
The strength of a BST is that you can perform all search, insertion and deletion operations in O(h) time complexity even in the worst case.
查找一个节点
According to the property of BST, for each node:
1. return the node if the target value is equal to the value of the node;
2. continue searching in the left subtree if the target value is less than the value of the node;
3. continue searching in the right subtree if the target value is larger than the value of the node.
LeetCode 700. Search in a Binary Search Tree
插入一个新节点
Similar to our search strategy, for each node, we will:
1. search the left or right subtrees according to the relation of the value of the node and the value of our target node;
2. repeat STEP 1 until reaching an external node;
3. add the new node as its left or right child depending on the relation of the value of the node and the value of our target node.
In this way, we add a new node and maintain the property of BST.
LeetCode 701. Insert into a Binary Search Tree
删除一个指定节点
1. If the target node has no child, we can simply remove the node.
2. If the target node has one child, we can use its child to replace itself.
3. If the target node has two children, replace the node with its in-order successor or predecessor node and delete that node.
LeetCode 450. Delete Node in a BST
两点注意:
1. 删除节点的方式很多;实际中,如果节点的值是个很复杂的对象,这种通过交换被删除节点和其后继的值的方式,在实际中可能代价会比较大,不如直接交换引用(如以下实现)。
2. 如果被删除节点的左右子树均为空,那么可以将其左子树作为其后继节点的左子树。不过这种方式有个缺点是,可能会加大树的高度,从而使树本身更加不平衡。以下实现中,通过改变左右子树的引用,返回其后继节点作为新的根。
删除指定节点 删除根节点其他相关算法
非递归中序遍历二叉树模板可以有效地解决一些问题。
LeetCode 94. Binary Tree Inorder Traversal
LeetCode 230. Kth Smallest Element in a BST
LeetCode 98. Validate Binary Search Tree
LeetCode 173. Binary Search Tree Iterator
引用:
Learn one iterative inorder traversal, apply it to multiple tree questions
网友评论