题目
给定二叉搜索树(BST)的根节点 root
和要插入树中的值 value
,将值插入二叉搜索树。 返回插入后二叉搜索树的根节点。 输入数据 保证 ,新值和原始二叉搜索树中的任意节点值都不同。
注意,可能存在多种有效的插入方式,只要树在插入后仍保持为二叉搜索树即可。 你可以返回 任意有效的结果 。
示例 1:
![](https://i-blog.csdnimg.cn/blog_migrate/be940ab2e07119dcd45e5d58370fc5de.jpeg)
输入:root = [4,2,7,1,3], val = 5 输出:[4,2,7,1,3,5] 解释:另一个满足题目要求可以通过的树是:![]()
示例 2:
输入:root = [40,20,60,10,30,50,70], val = 25 输出:[40,20,60,10,30,50,70,null,null,25]
示例 3:
输入:root = [4,2,7,1,3,null,null,null,null,null,null], val = 5 输出:[4,2,7,1,3,5]
提示:
- 树中的节点数将在
[0, 104]
的范围内。 -108 <= Node.val <= 108
- 所有值
Node.val
是 独一无二 的。 -108 <= val <= 108
- 保证
val
在原始BST中不存在。
分析
没什么好分析的,就是模板代码,理解记住就行了,有时间可以画一下图帮助自己理解。
public class TreeNode {
public int val;
public TreeNode left;
public TreeNode right;
public TreeNode() {}
public TreeNode(int val) { this.val = val; }
public TreeNode(int val, TreeNode left, TreeNode right) {
this.val = val;
this.left = left;
this.right = right;
}
}
递归实现
public class Main {
public TreeNode insertIntoBST(TreeNode root, int val) {
if (root == null) return new TreeNode(val);
return dfs(root, val);
}
private TreeNode dfs(TreeNode root, int val) {
if (root == null) return root;
if (root.val < val) {
if (root.right == null) {
root.right = new TreeNode(val);
} else {
dfs(root.right, val);
}
} else {
if (root.left == null) {
root.left = new TreeNode(val);
} else {
dfs(root.left, val);
}
}
return root;
}
}
栈实现
public class Deques {
public TreeNode insertIntoBST(TreeNode root, int val) {
if (root == null) return new TreeNode(val);
Deque<TreeNode> stack = new ArrayDeque<>();
stack.push(root);
while (!stack.isEmpty()) {
TreeNode n = stack.pop();
if (n.val < val) {
if (n.right == null) n.right = new TreeNode(val);
else stack.push(n.right);
} else {
if (n.left == null) n.left = new TreeNode(val);
else stack.push(n.left);
}
}
return root;
}
}