算法学习day22二叉树part08-450、701、235
package LeetCode.Treepart08; public class DeleteNodeBST_450 { public TreeNode deleteNode(TreeNode root, int key) { root = delete(root,key); return root; } private TreeNode delete(TreeNode root, int key) { if (root == null) return null; if (root.val > key) { root.left = delete(root.left,key); } else if (root.val < key) { root.right = delete(root.right,key); } else { if (root.left == null) return root.right; if (root.right == null) return root.left; TreeNode tmp = root.right; while (tmp.left != null) { tmp = tmp.left; } root.val = tmp.val; root.right = delete(root.right,tmp.val); } return root; } }
package LeetCode.Treepart08; /** * 701. 二叉搜索树中的插入操作 * 给定二叉搜索树(BST)的根节点 root和要插入树中的值value,将值插入二叉搜索树。 返回插入后二叉搜索树的根节点。 * 输入数据 保证 ,新值和原始二叉搜索树中的任意节点值都不同。 * 注意,可能存在多种有效的插入方式,只要树在插入后仍保持为二叉搜索树即可。 你可以返回 任意有效的结果 。 * */ public class InsertintoBinarySearchTree_701 { public TreeNode insertIntoBST(TreeNode root, int val) { if (root == null) return new TreeNode(val); TreeNode newRoot = root; TreeNode pre = root; while (root != null) { pre = root; if (root.val > val) { root = root.left; } else if (root.val < val) { root = root.right; } } if (pre.val > val) { pre.left = new TreeNode(val); } else { pre.right = new TreeNode(val); } return newRoot; } }
package LeetCode.Treepart08; /** * 235. 二叉搜索树的最近公共祖先 * 给定一个二叉搜索树, 找到该树中两个指定节点的最近公共祖先。 * 百度百科中最近公共祖先的定义为:“对于有根树 T 的两个结点 p、q,最近公共祖先表示为一个结点 x,满足 x 是 p、q 的祖先且 x 的深度尽可能大(一个节点也可以是它自己的祖先)。” * 例如,给定如下二叉搜索树: root = [6,2,8,0,4,7,9,null,null,3,5] * * */ public class LowestCommonAncestorBinarySearchTree_235 { public TreeNode lowestCommonAncestor(TreeNode root, TreeNode p, TreeNode q) { if (root.val > p.val && root.val > q.val) return lowestCommonAncestor(root.left, p, q); if (root.val < p.val && root.val < q.val) return lowestCommonAncestor(root.right, p, q); return root; } }
分类:
算法学习
【推荐】国内首个AI IDE,深度理解中文开发场景,立即下载体验Trae
【推荐】编程新体验,更懂你的AI,立即体验豆包MarsCode编程助手
【推荐】抖音旗下AI助手豆包,你的智能百科全书,全免费不限次数
【推荐】轻量又高性能的 SSH 工具 IShell:AI 加持,快人一步
· 【自荐】一款简洁、开源的在线白板工具 Drawnix
· 没有Manus邀请码?试试免邀请码的MGX或者开源的OpenManus吧
· 无需6万激活码!GitHub神秘组织3小时极速复刻Manus,手把手教你使用OpenManus搭建本
· C#/.NET/.NET Core优秀项目和框架2025年2月简报
· DeepSeek在M芯片Mac上本地化部署