235. 二叉搜索树的最近公共祖先
如果不是二叉搜索树的话,使用后序遍历回溯。
二叉搜索树的话,如果 p 和 q 的值的大小刚好在 root的两边, (p < root < q or q < root < q),则 root 为p,q的最近公共祖先。
代码:
class Solution {
public TreeNode lowestCommonAncestor(TreeNode root, TreeNode p, TreeNode q) {
// if (root == null) return null;
if (root.val > p.val && root.val > q.val) return lowestCommonAncestor(root.left, p, q);
if (root.val < p.val && root.val < q.val) return lowestCommonAncestor(root.right, p, q);
return root;
}
}
701.二叉搜索树中的插入操作
其实不需要改变树结构,不需要考虑插入后的树是否为二叉搜索树。
利用二叉搜索树树的特点,遇到null 则创建节点,并返回。
450.删除二叉搜索树中的节点
难点在于调整删除节点的左右子树。分清楚情况分别处理即可。
- 左右子树均为空:直接返回空
- 左子树不为空,右子树为空:直接返回左孩子
- 左子树为空,右子树不为空:直接返回右孩子
- 左右子树都不为空:需要将左子树移动到右子树的最左边节点的左孩子。
if (root.left == null && root.right == null) return null;
else if (root.left != null && root.right == null) return root.left;
else if (root.left == null && root.right != null) return root.right;
else {
TreeNode temp = root.right;
while (temp.left != null) {
temp = temp.left;
}
temp.left = root.left;
return root.right;
}
简洁代码:
if (root.left == null) return root.right;
if (root.right == null) return root.left;
TreeNode temp = root.right;
while (temp.left != null) {
temp = temp.left;
}
temp.left = root.left;
return root.right;