235. 二叉搜索树的最近公共祖先
对比直接在树里找最近公共祖先,这题可以利用二叉搜索树的性质,让题解更简单。
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; // root.val == p.val || root.val == q.val
}
}
701. 二叉搜索树中的插入操作
*/
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;
}
}
450. 删除二叉搜索树中的节点
来源:labuladong的算法小抄
情况 1:A 恰好是末端节点,两个子节点都为空,那么它可以当场去世了:
情况 2:A 只有一个非空子节点,那么它要让这个孩子接替自己的位置:
情况 3:A 有两个子节点,麻烦了,为了不破坏 BST 的性质,A 必须找到左子树中最大的那个节点或者右子树中最小的那个节点来接替自己,我的解法是用右子树中最小节点来替换:
class Solution {
public TreeNode deleteNode(TreeNode root, int key) {
if(root == null)return null;
if(root.val == key){
// 处理情况1和2
if(root.left == null)return root.right;
if(root.right == null)return root.left;
// 处理情况3
// 获得右子树的最小节点
TreeNode minNode = getMin(root.right);
// 删除右子树最小的节点
root.right = deleteNode(root.right, minNode.val);
// 用右子树最小的节点替换root节点
minNode.left = root.left;
minNode.right = root.right;
root = minNode;
}
else if(root.val > key){
root.left = deleteNode(root.left, key);
}
else if(root.val < key){
root.right = deleteNode(root.right, key);
}
return root;
}
private TreeNode getMin(TreeNode node){
// BST最左边的就是最小的
while(node.left != null)node = node.left;
return node;
}
}