1、二叉搜索树的节点添加操作
public class Solution {
/**
* @param root: The root of the binary search tree.
* @param node: insert this node into the binary search tree
* @return: The root of the new binary search tree.
*/
public TreeNode insertNode(TreeNode root, TreeNode node) {
if(root==null){
return node;
}else if(root.val<=node.val){
root.right=insertNode(root.right,node);
}else{
root.left=insertNode(root.left,node);
}
return root;
}
}
2、二叉搜索树的节点删除操作
思路
若要删除一个BST的一个结点,需要考虑如下三种情况:
- 需要删除的节点下并没有其他子节点
- 需要删除的节点下有一个左子节点(或者右子节点)
- 需要删除的节点下有两个子节点(左右子节点都存在)
对这三种情况分别采取的措施是:
- 直接删除此结点
- 删除此结点,将此结点父节点连接到此结点左(或者右)子树
- 找出此结点右子树中的最小结点(或者找出左子节点的最大节点),用以代替要删除的结点,然后删除右子树中的此最小结点(或者删除左子树中的此最大节点)
java代码
/**
public TreeNode deleteNode(TreeNode root, int key) {
if(root == null){
return null;
}
if(key < root.val){
root.left = deleteNode(root.left, key);
}else if(key > root.val){
root.right = deleteNode(root.right, key);
}else{
if(root.left == null){
return root.right;
}else if(root.right == null){
return root.left;
}
TreeNode minNode = findMin(root.right);
root.val = minNode.val;
root.right = deleteNode(root.right, root.val);
}
return root;
}
private TreeNode findMin(TreeNode node){
while(node.left != null){
node = node.left;
}
return node;
}