题目:235. 二叉搜索树的最近公共祖先 - 力扣(LeetCode)
思路/想法:
当根节点值介于左节点和右节点之间时,当前节点就是左右节点的最近公共祖先。
代码实现:
class Solution {
public TreeNode lowestCommonAncestor(TreeNode root, TreeNode p, TreeNode q) {
while (true) {
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;
}
}
题目: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);
}
if (root.val < val) {
root.right = insertIntoBST(root.right, val);
}
return root;
}
}
题目:450. 删除二叉搜索树中的节点 - 力扣(LeetCode)
思路/想法:
首先前序遍历,分情况讨论。
代码实现:
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;
}
}