二叉树part7
二叉树part7
235. 二叉搜索树的最近公共祖先 - 力扣(LeetCode)
BST的性质让其做题很容易有思路
原话:
而递归遍历顺序,本题就不涉及到 前中后序了(这里没有中节点的处理逻辑,遍历顺序无所谓了)。
class Solution {
public TreeNode lowestCommonAncestor(TreeNode root, TreeNode p, TreeNode q) {
if(root == null){
return root;
}
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;
}
}
}
701. 二叉搜索树中的插入操作 - 力扣(LeetCode)
很简单的题目,判断当前节点状态,然后更新要操作的位置就可以,没看讲解,秒了
迭代写法:
class Solution {
public TreeNode insertIntoBST(TreeNode root, int val) {
if(root == null){
return new TreeNode(val);
}
TreeNode cur = root;
while(root != null){
if(val > root.val && root.right != null){
root = root.right;
}else if(val > root.val && root.right == null){
root.right = new TreeNode(val);
return cur;
}else if(val < root.val && root.left != null){
root = root.left;
}else if(val < root.val && root.left == null){
root.left = new TreeNode(val);
return cur;
}
}
return cur;
}
}
递归写法:
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);
}else if(val < root.val){
root.left = insertIntoBST(root.left, val);
}
return root;
}
}
450. 删除二叉搜索树中的节点 - 力扣(LeetCode)
感觉之前做过这种题目,最复杂的情况理解起来也很简单
本题重点就是处理key == root.val时的四种情况,最复杂的是要删除的节点左右子树都不为空时
那么处理方式就是把左子树放在右子树的最左下,然后让root == 右子树根节点
class Solution {
public TreeNode deleteNode(TreeNode root, int key) {
if(root == null){
return root;
}
if(key == root.val){
if(root.left == null && root.right == null){
root = null;
}else if(root.left != null && root.right == null){
root = root.left;
}else if(root.left == null && root.right != null){
root = root.right;
}else if(root.left != null && root.right != null){
TreeNode cur = root.right;
while(cur.left != null){
cur = cur.left;
}
cur.left = root.left;
root = root.right;
}
}else if(key > root.val){
root.right = deleteNode(root.right, key);
}else if(key < root.val){
root.left = deleteNode(root.left, key);
}
return root;
}
}
浙公网安备 33010602011771号