1.二叉搜索树的最近公共祖先
class Solution {
public TreeNode lowestCommonAncestor(TreeNode root, TreeNode p, TreeNode q) {
if (root.val > p.val && root.val > q.val) return lowestCommonAncestor(root.left, p, q); //返回left
if (root.val < p.val && root.val < q.val) return lowestCommonAncestor(root.right, p, q); //返回right
return root;
}
}
2.二叉搜索树中的插入操作
不考虑改变树的结构,使用递归法
class Solution {
public TreeNode insertIntoBST(TreeNode root, int val) {
if(root == null){
return new TreeNode(val);
}
if(root.val < val){
root.right = insertIntoBST(root.right, val);
}
if(root.val > val){
root.left = insertIntoBST(root.left, val);
}
return root;
}
}
3.删除二叉搜索树中的节点
class Solution {
public TreeNode deleteNode(TreeNode root, int key) {
if (root == null) return root;
if (root.val == key) {
if (root.left == null) { //只有一侧的子节点,此时直接返回
return root.right;
} else if (root.right == null) {
return root.left;
} else { //找到需要删除的节点
TreeNode cur = root.right;
while (cur.left != null) { //找到比删除的节点大的数(最小大于)
cur = cur.left;
}
cur.left = root.left; //将删除节点的左子树赋给新找到的值
root = root.right; //直接返回右子树
return root;
}
}
if (root.val > key) root.left = deleteNode(root.left, key);
if (root.val < key) root.right = deleteNode(root.right, key);
return root;
}
}