代码随想录算法训练营第十七天|235. 二叉搜索树的最近公共祖先、701.二叉搜索树中的插入操作、450.删除二叉搜索树中的节点
235. 二叉搜索树的最近公共祖先
题目链接:. - 力扣(LeetCode)
文章讲解:代码随想录
思路: 由于搜索二叉树的性质,找到的第一个节点的值在所要查找的两个节点的值的区间内就是它们的最近公共祖先。
/**
* Definition for a binary tree node.
* public class TreeNode {
* int val;
* TreeNode left;
* TreeNode right;
* TreeNode(int x) { val = x; }
* }
*/
class Solution {
public TreeNode lowestCommonAncestor(TreeNode root, TreeNode p, TreeNode q) {
if (root == null) {
return null;
}
if (root.val > p.val && root.val > q.val) {
TreeNode left = lowestCommonAncestor(root.left, p, q);
return left;
} else if (root.val < p.val && root.val < q.val) {
TreeNode right = lowestCommonAncestor(root.right, p, q);
return right;
} else {
return root;
}
}
}
701.二叉搜索树中的插入操作
题目链接:. - 力扣(LeetCode)
文章讲解:代码随想录
思路:按插入的节点为叶子节点思路来插入。
/**
* Definition for a binary tree node.
* public class TreeNode {
* int val;
* TreeNode left;
* TreeNode right;
* TreeNode() {}
* TreeNode(int val) { this.val = val; }
* TreeNode(int val, TreeNode left, TreeNode right) {
* this.val = val;
* this.left = left;
* this.right = right;
* }
* }
*/
class Solution {
TreeNode pre = null;
public TreeNode insertIntoBST(TreeNode root, int val) {
if (root == null) {
return new TreeNode(val);
}
insertNewNode(root, val);
return root;
}
public void insertNewNode(TreeNode root, int val) {
if (root == null) {
TreeNode treeNode = new TreeNode(val);
if (pre.val > val) {
pre.left = treeNode;
} else {
pre.right = treeNode;
}
return;
}
pre = root;
if (root.val > val) {
insertNewNode(root.left, val);
}else {
insertNewNode(root.right, val);
}
}
}
450.删除二叉搜索树中的节点
题目链接:. - 力扣(LeetCode)
文章讲解:代码随想录
视频讲解:调整二叉树的结构最难!| LeetCode:450.删除二叉搜索树中的节点_哔哩哔哩_bilibili
思路:1.如果要删除的节点是叶子节点,则直接删除。2.如果要删除的节点只有一个子树,另一颗子树为空,则返回它不为空的子树的根节点。3.如果要删除的节点左右子树都不为空,则将该节点的左子树位置变为右子树的最左边的叶子节点的左节点,然后返回要删除节点的右节点。
/**
* Definition for a binary tree node.
* public class TreeNode {
* int val;
* TreeNode left;
* TreeNode right;
* TreeNode() {}
* TreeNode(int val) { this.val = val; }
* TreeNode(int val, TreeNode left, TreeNode right) {
* this.val = val;
* this.left = left;
* this.right = right;
* }
* }
*/
class Solution {
public TreeNode deleteNode(TreeNode root, int key) {
if (root == null) {
return root;
}
if (root.val == key) {
if (root.right == null) {
return root.left;
}
if (root.left == null) {
return root.right;
}
TreeNode temp = root.right;
while (temp.left != null) {
temp = temp.left;
}
temp.left = root.left;
return root.right;
}
if (root.val > key) {
root.left = deleteNode(root.left, key);
} else {
root.right = deleteNode(root.right, key);
}
return root;
}
}
原文地址:https://blog.csdn.net/qq_73932604/article/details/143494028
免责声明:本站文章内容转载自网络资源,如本站内容侵犯了原著者的合法权益,可联系本站删除。更多内容请关注自学内容网(zxcms.com)!