题目:
给定二叉搜索树(BST)的根节点和要插入树中的值,将值插入二叉搜索树。 返回插入后二叉搜索树的根节点。 保证原始二叉搜索树中不存在新值。
注意,可能存在多种有效的插入方式,只要树在插入后仍保持为二叉搜索树即可。 你可以返回任意有效的结果。
示例:
代码:
- 解法一
/**
* Definition for a binary tree node.
* public class TreeNode {
* int val;
* TreeNode left;
* TreeNode right;
* TreeNode(int x) { val = x; }
* }
*/
//递归的思想
class Solution {
public TreeNode insertIntoBST(TreeNode root, int val) {
if(root==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;
}
}
- 别人的代码
/**
* Definition for a binary tree node.
* public class TreeNode {
* int val;
* TreeNode left;
* TreeNode right;
* TreeNode(int x) { val = x; }
* }
*/
//迭代的思想
class Solution {
public TreeNode insertIntoBST(TreeNode root, int val) {
if (root == null) {
root = new TreeNode(val);
}
TreeNode node = root;
while (node != null) {
if (node.val > val) { //在其左子树中插入
if (node.left == null) { 当其左子树为空时 添加元素
node.left = new TreeNode(val);
break;
}
node = node.left;
}
if (node.val < val) { //在其右子树上插入元素
if (node.right == null) { //当其右子树为空时 添加元素
node.right = new TreeNode(val);
break;
}
node = node.right;
}
}
return root; //返回跟结点
}
}