235. 二叉搜索树的最近公共祖先
235. 二叉搜索树的最近公共祖先 - 力扣(LeetCode)
二叉搜索树中的最近公共祖先要比普通二叉树的简单一些,如果p和q在root的两侧,那么直接返回root即可
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);
} else if (root.val < p.val && root.val < q.val) {
return lowestCommonAncestor(root.right, p, q);
} else {
return root;
}
}
}
701.二叉搜索树中的插入操作
701. 二叉搜索树中的插入操作 - 力扣(LeetCode)
简单起见,把数据都插入到叶子节点
class Solution {
public TreeNode insertIntoBST(TreeNode root, int val) {
if (root == null) {
return new TreeNode(val);
}
if (root.val > val) {
root.left = insertIntoBST(root.left, val);
} else if (root.val < val) {
root.right = insertIntoBST(root.right, val);
}
//最后把根节点返回
return root;
}
}
450.删除二叉搜索树中的节点
450. 删除二叉搜索树中的节点 - 力扣(LeetCode)
对于要删除的节点,一共分为5中情况
- 不存在该节点
- 该节点左右孩子均为空
- 左孩子为空,右孩子不为空
- 左孩子不为空,右孩子为空
- 左右孩子都不为空
其中第5种情况较复杂,可以返回节点的右孩子,然后将左孩子插入到右孩子的孩子节点处,因为左孩子一定比右孩子小,所以需要插入右孩子的最左下角的左孩子
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;
}
}