1.二叉搜索树的最近公共祖先
2.二叉搜索树中的插入操作
3.删除搜索二叉树中的节点
1.二叉搜索树的最近公共祖先
思路:这道题比普通的二叉树要好做,因为是有序树,所有如果中间节点是 q 和 p 的公共祖先,那么中节点的数组 一定是在 [p, q]区间的。即 中节点 > p && 中节点 < q 或者 中节点 > q && 中节点 < p。
递归做法:
class Solution {
public TreeNode lowestCommonAncestor(TreeNode root, TreeNode p, TreeNode q) {
while(root!=null){
if(root.val > p.val && root.val > q.val) root = root.left;
else if(root.val < p.val && root.val < q.val) root = root.right;
else break;
}
return root;
}
}
迭代法:
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);
else if(root.val < p.val && root.val < q.val) return lowestCommonAncestor(root.right,p,q);
else return root;
}
}
2.二叉搜索树中的插入操作
思路:只要遍历二叉搜索树,找到空节点 插入元素就可以了,不需要遍历所有节点,按照大小左右查找就好了
class Solution {
public TreeNode insertIntoBST(TreeNode root, int val) {
if(root == null) {
TreeNode node = new TreeNode(val);
return node;
}
if(val > root.val) root.right = insertIntoBST(root.right,val);
else if(val < root.val) root.left = insertIntoBST(root.left,val);
return root;
}
}
3.删除搜索二叉树中的节点
思路:这道题要分类讨论:
- 第一种情况:没找到删除的节点,遍历到空节点直接返回了
- 找到删除的节点
- 第二种情况:左右孩子都为空(叶子节点),直接删除节点, 返回NULL为根节点
- 第三种情况:删除节点的左孩子为空,右孩子不为空,删除节点,右孩子补位,返回右孩子为根节点
- 第四种情况:删除节点的右孩子为空,左孩子不为空,删除节点,左孩子补位,返回左孩子为根节点
- 第五种情况:左右孩子节点都不为空,则将删除节点的左子树头结点(左孩子)放到删除节点的右子树的最左面节点的左孩子上,返回删除节点右孩子为新的根节点。
第五种情况就是这样:比较难想到
class Solution {
public TreeNode deleteNode(TreeNode root, int key) {
if(root == null) return null;
if(root.val == key) {
if(root.left == null && root.right == null){
return null;
}else if(root.left == null && root.right != null){
return root.right;
}else if(root.left != null && root.right == null){
return root.left;
}else{
TreeNode cur = root.right;
while(cur.left != null){
cur = cur.left;
}
cur.left = root.left;
return root.right;
}
}
if(key > root.val) root.right = deleteNode(root.right,key);
if(key < root.val) root.left = deleteNode(root.left,key);
return root;
}
}
学习时长:2h
总结:对二叉搜索树的结构变换更加熟练。