JAVA版本
思路:本题的思想较为简单,直接找到适合插入的结点来进行插入即可
解法一:
递归法:
class Solution {
public TreeNode insertIntoBST(TreeNode root, int val) {
if(root ==null) {
return new TreeNode(val);
}
if(root.val < val){
root.right = insertIntoBST(root.right,val);
} else {
root.left = insertIntoBST(root.left,val);
}
return root;
}
}
解法二:
迭代法:
迭代法的思想就是找到最适合插入的结点,在最适合插入的结点来进行插入操作。
class Solution {
public TreeNode insertIntoBST(TreeNode root, int val) {
if (root == null) return new TreeNode(val);
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;
}
}
if (pre.val > val) {
pre.left = new TreeNode(val);
} else {
pre.right = new TreeNode(val);
}
return newRoot;
}
}