[leetCode]701. 二叉搜索树中的插入操作
题目
题目:链接:https://leetcode-cn.com/problems/insert-into-a-binary-search-tree
给定二叉搜索树(BST)的根节点和要插入树中的值,将值插入二叉搜索树。 返回插入后二叉搜索树的根节点。 输入数据 保证 ,新值和原始二叉搜索树中的任意节点值都不同。
注意,可能存在多种有效的插入方式,只要树在插入后仍保持为二叉搜索树即可。 你可以返回 任意有效的结果 。
递归
class Solution {
public TreeNode insertIntoBST(TreeNode root, int val) {
if (root == null) { // 遍历的节点为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;
}
}
迭代
class Solution {
public TreeNode insertIntoBST(TreeNode root, int val) {
if (root == null) {
return new TreeNode(val);
}
TreeNode cur = root;
TreeNode parent = null;
while (cur != null) {
parent = cur; // 在移动之前记录父节点
if (cur.val > val) cur = cur.left;
else if (cur.val <= val) cur = cur.right;
}
if (parent.val > val) {
parent.left = new TreeNode(val);
} else {
parent.right = new TreeNode(val);
}
return root;
}
}
【推荐】国内首个AI IDE,深度理解中文开发场景,立即下载体验Trae
【推荐】博客园2025新款「AI繁忙」系列T恤上架,前往周边小店选购
【推荐】凌霞软件回馈社区,携手博客园推出1Panel与Halo联合会员
【推荐】轻量又高性能的 SSH 工具 IShell:AI 加持,快人一步