给定二叉搜索树(BST)的根节点和要插入树中的值,将值插入二叉搜索树。 返回插入后二叉搜索树的根节点。 保证原始二叉搜索树中不存在新值。
注意,可能存在多种有效的插入方式,只要树在插入后仍保持为二叉搜索树即可。 你可以返回任意有效的结果。
根据搜索二叉树的特性进行插入
public TreeNode insertIntoBST(TreeNode root, int val) {
TreeNode pre=root;
TreeNode cur=root;
if(root==null)
return new TreeNode(val);
while(cur.val !=val){
if(val<cur.val){
pre=cur;
cur=cur.left;
}else{
pre=cur;
cur=cur.right;
}
if(cur==null){
if(pre.val<val)
pre.right=new TreeNode(val);
else
pre.left=new TreeNode(val);
return root;
}
}
return root;
}