二叉搜索树中的插入操作
给定二叉搜索树(BST)的根节点和要插入树中的值,将值插入二叉搜索树。 返回插入后二叉搜索树的根节点。 保证原始二叉搜索树中不存在新值。
注意,可能存在多种有效的插入方式,只要树在插入后仍保持为二叉搜索树即可。 你可以返回任意有效的结果。
递归
/**
* Definition for a binary tree node.
* public class TreeNode {
* int val;
* TreeNode left;
* TreeNode right;
* TreeNode() {}
* TreeNode(int val) { this.val = val; }
* TreeNode(int val, TreeNode left, TreeNode right) {
* this.val = val;
* this.left = left;
* this.right = right;
* }
* }
*/
class Solution {
public TreeNode insertIntoBST(TreeNode root, int val) {
// 找到空位置插入新节点
if(root == null) {
return new TreeNode(val);
}
// if (root.val == val)
// BST 中一般不会插入已存在元素
if(root.val < val) {
root.right = insertIntoBST(root.right, val);
}
if(root.val > val) {
root.left = insertIntoBST(root.left, val);
}
return root;
}
}
迭代
class Solution {
public TreeNode insertIntoBST(TreeNode root, int val) {
TreeNode node = root;
while (node != null) {
// insert into the right subtree
if (val > node.val) {
// insert right now
if (node.right == null) {
node.right = new TreeNode(val);
return root;
}
else node = node.right;
}
// insert into the left subtree
else {
// insert right now
if (node.left == null) {
node.left = new TreeNode(val);
return root;
}
else node = node.left;
}
}
return new TreeNode(val);
}
}