1. 二叉搜索树的最近公共祖先
235. 二叉搜索树的最近公共祖先 - 力扣(LeetCode)
有序的,可以根据值判断pq在哪一边
pq要么在左右子树中一边 搜索其中一边即可
要么就是 pq中的一个在根节点,另一个在其中一颗子树,返回根节点即可
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);
if(root.val < p.val && root.val < q.val) return lowestCommonAncestor(root.right, p, q);
return root;
}
}
2. 二叉搜索树中的插入操作
701. 二叉搜索树中的插入操作 - 力扣(LeetCode)
这题要想明白,要插入的节点始终能在叶子节点下找到一个它的位置
class Solution {
public TreeNode insertIntoBST(TreeNode root, int val) {
if(root == null) return new TreeNode(val);
if(val > root.val) root.right = insertIntoBST(root.right, val);
if(val < root.val) root.left = insertIntoBST(root.left, val);
return root;
}
}
3. 删除二叉搜索树中的节点
450. 删除二叉搜索树中的节点 - 力扣(LeetCode)
1. 找不到key
2. 找到key
2.1 叶子节点
将null返回给上一层
2.2 左为null
将右子树返回给上一层
2.3 右为null
将左子树返回给上一层
2.4 左右都不为null
将左子树挂到右子树的最左节点(该节点是第一个比左子树中最大节点大的,保证右子树的有序性)
将右子树返回给父节点
class Solution {
public TreeNode deleteNode(TreeNode root, int key) {
if(root == null) return root;//1
if(root.val == key){ //2
if(root.left == null && root.right == null) //2.1
return null;
if(root.left == null) //2.2
return root.right;
if(root.right == null) //2.3
return root.left;
TreeNode cur = root.right; //2.4
while(cur.left != null)
cur = cur.left;
cur.left = root.left;
return root.right;
}
if(key < root.val) root.left = deleteNode(root.left, key);
if(key > root.val) root.right = deleteNode(root.right, key);
return root;
}
}