leetcode235. 二叉搜索树的最近公共祖先
注意:√
- 昨天在解决二叉树LCA问题的时候看到了Labuladong书中的内容,让这题变得简单,核心是要处理一个
find(root, val1, val2)
的问题 - 注意一开始会有担心觉得为什么root节点在
val1<=root<=val2
就是最后的结果,因为root节点是分界点,分界的root.left一定是比root小的,必然不会存在val2的节点。 - 即root节点就是分支的点,一定要注意这个问题
public TreeNode lowestCommonAncestor(TreeNode root, TreeNode p, TreeNode q) {
int val1 = Math.min(p.val, q.val);
int val2 = Math.max(p.val, q.val);
return find(root, val1, val2);
}
private TreeNode find(TreeNode root, int val1, int val2) {
if (root == null){
return null;
}
if (root.val> val2){
return find(root.left, val1, val2);
}
if (root.val< val1){
return find(root.right, val1, val2);
}
return root;
}
leetcode 701.二叉搜索树中的插入操作
注意:×
- 第一遍写错了,直接将字数返回了,但是实际上正是用
root.left = insertIntoBST(root.left, val);
的方式将子树接在上面
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;
}
// public TreeNode insertIntoBST(TreeNode root, int val) {
// if (root == null) {
// return new TreeNode(val);
// }
// if (root.val > val) {
// return insertIntoBST(root.left, val);
// }
// if (root.val < val) {
// return insertIntoBST(root.right, val);
// }
// return root;
// }
leetcode450.删除二叉搜索树中的节点
注意:√
- 详细看完了Labuladong以后复现的,注意回头看
public TreeNode deleteNode(TreeNode root, int key) {
if (root == null){
return null;
}
if (root.val == key){
if (root.left == null){
return root.right;
}
if (root.right == null){
return root.left;
}
TreeNode minNode = getMin(root.right);
root.val = minNode.val;
root.right = deleteNode(root.right, minNode.val);
} else if (root.val > key) {
root.left = deleteNode(root.left, key);
} else if (root.val < key) {
root.right = deleteNode(root.right, key);
}
return root;
}
private TreeNode getMin(TreeNode right) {
while (right.left!= null){
right = right.left;
}
return right;
}