【找到要插入的点的父节点】思路就是二分查找那种的,先查找这个点应该插入的位置,判定条件为null,那么null的父节点就是第一个小于这个插入点的节点,所以直接创建节点作为他的左儿子即可;但是也有例外,就是要查找的点很大很大,这样应该是做右儿子才行。因此需要在最后插入的时候做一次判断。
class Solution {
public TreeNode insertIntoBST(TreeNode root, int val) {
if(root == null) return new TreeNode(val);
TreeNode pre = new TreeNode(), dummy = root;
while(true){
if(root == null) break;
pre = root;
if(root.val < val) root = root.right;
else root = root.left;
}
if(pre.val < val) pre.right = new TreeNode(val);
else pre.left = new TreeNode(val);
return dummy;
}
}
【优化】 其实还有更好的方法,就是在查找的过程中直接把这件事情做了,如果:
1.查找节点不为null,就根据大小继续向左向右查找;
2.查找节点为null,创建新节点替换null
class Solution {
public TreeNode insertIntoBST(TreeNode root, int val) {
if(root == null) return new TreeNode(val);
TreeNode node = root;
while(node != null){
if(node.val > val){
if(node.left == null) {
node.left = new TreeNode(val);
return root;
}
else node = node.left;
}else{
if(node.right == null) {
node.right = new TreeNode(val);
return root;
}
else node = node.right;
}
}
return root;
}
}