235二叉搜索树的最近公共祖先
https://leetcode.cn/problems/lowest-common-ancestor-of-a-binary-search-tree/
从上到下遍历时第一次遇到的在两数中间的点或相等的即为LCA, 遍历的方式可以递归也可以迭代,按照比较的结果只走左右里的其中一边。
class Solution { //从上到下遍历时第一次遇到的在两数中间的点或相等的即为LCA
public TreeNode lowestCommonAncestor(TreeNode root, TreeNode p, TreeNode q) {
if (root.val < p.val && root.val < q.val) {
return lowestCommonAncestor(root.right, p, q);
} else if(root.val > p.val && root.val > q.val) {
return lowestCommonAncestor(root.left, p, q);
} else { // root == null || root == p || root == q || root.val > p.val && root.val < q.val || root.val > q.val && root.val < p.val
return root;
}
}
}
class Solution { //从上到下遍历时第一次遇到的在两数中间的点或相等的即为LCA
public TreeNode lowestCommonAncestor(TreeNode root, TreeNode p, TreeNode q) {
while (root != null) {
if (root.val < p.val && root.val < q.val) {
root = root.right;
} else if (root.val > p.val && root.val > q.val) {
root = root.left;
} else {
return root;
}
}
return null;
}
}
701 二叉搜索树中的插入操作
https://leetcode.cn/problems/insert-into-a-binary-search-tree/description/
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;
}
}
class Solution { // 迭代
public TreeNode insertIntoBST(TreeNode root, int val) {
if (root == null) return new TreeNode(val);
TreeNode cur = root;
while (cur.val != val) {
if (cur.val > val) {
if (cur.left == null) {
cur.left = new TreeNode(val);
break;
} else {
cur = cur.left;
}
} else {
if (cur.right == null) {
cur.right = new TreeNode(val);
break;
} else {
cur = cur.right;
}
}
}
return root;
}
}
450 删除二叉搜索树中的节点
https://leetcode.cn/problems/delete-node-in-a-bst/description/
class Solution { //不会增加高度
public TreeNode deleteNode(TreeNode root, int key) {
if (root == null) return root;
if (root.val > key) {
root.left = deleteNode(root.left, key);
} else if (root.val < key) {
root.right = deleteNode(root.right, key);
} else { // root.val == key
if (root.right == null) {
return root.left;
} else { //要找右子树里的最小值提上去,被提上去的树的右孩子要给他的爷爷管
TreeNode mostLeft = root.right;
TreeNode parent = root;
while (mostLeft.left != null) { //右子树最小值在不在根,在左子树,往左走到底
parent = mostLeft;
mostLeft = mostLeft.left;
}
if (mostLeft != root.right) { //右子树根已经是该树最小值,while里一步都没走
parent.left = mostLeft.right; //mostLeft要被提上去了,它的右孩子要给mostLeft的爸爸管
mostLeft.right = root.right;
}
mostLeft.left = root.left;
return mostLeft;
}
}
return root;
}
}