https://leetcode-cn.com/problems/insert-into-a-binary-search-tree/
因为是BST,所以我第一个想到的就是 按照大小来往下走。用的是迭代的方法,至于遍历,还没想好,不过这个题自己写出来了。
记得使用虚拟头节点保留根节点。
class Solution {
public TreeNode insertIntoBST(TreeNode root, int val) {
TreeNode dummyNode = root;
if(root == null) return new TreeNode(val);
while(root != null){
if(val < root.val && root.left != null) root = root.left;
else if(val > root.val && root.right != null) root = root.right;
else{
if(val < root.val){
root.left = new TreeNode(val); break;
}
else{
root.right = new TreeNode(val); break;
}
}
}
return dummyNode;
}
}