1. 题目
2. 思路
(1) 模拟法
- 利用递归找到插入位置插入即可。
3. 代码
import javax.naming.ldap.PagedResultsControl;
public class Test {
public static void main(String[] args) {
}
}
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);
}
insert(root, val);
return root;
}
private void insert(TreeNode root, int val) {
if (val < root.val) {
if (root.left == null) {
root.left = new TreeNode(val);
} else {
insert(root.left, val);
}
} else {
if (root.right == null) {
root.right = new TreeNode(val);
} else {
insert(root.right, val);
}
}
}
}