class Solution {
// 迭代法
public TreeNode insertIntoBST(TreeNode root, int val) {
if(root == null){
return new TreeNode(val);
}
// 这里用newRoot来记录最后要返回的根结点,这里采用的插入方式是,遍历搜索树、找到位置就插入,
// 对于插入结点是根节点的情况其实是可以避免的,因为不需要调整树结构可以在空余位置直接插入
TreeNode newRoot = root;
TreeNode pre = root;
while (root != null){
pre = root;
if(root.val > val){// 当前值大于要插入的值 向左搜索
root = root.left;
}else if(root.val < val){// 当前值小于要插入的值 向右搜索
root = root.right;
}
}
// 退出while循环,表示找到要插入的位置root, 此时的root为null
// 而pre则是前一个结点,root要么为pre.left 要么为pre.right 因此下面需要做判断
if(pre.val > val){// 如果pre.val 大于val , 则在当前结点的左结点处插入
pre.left = new TreeNode(val);
}else{
pre.right = new TreeNode(val);
}
return newRoot;
}
// 递归法:
public TreeNode insertIntoBST1(TreeNode root, int val) {
if(root == null){// 如果当前节点为空,也就意味着val找到了合适的位置,此时创建节点直接返回。
return new TreeNode(val);
}
if(root.val < val){
root.right = insertIntoBST1(root.right, val); // 递归创建右子树
}else if(root.val > val){
root.left = insertIntoBST1(root.left, val); // 递归创建左子树
}
return root;
}
}
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;
}
}