701. 二叉搜索树中的插入操作
深度优先搜索
class Solution {
public TreeNode insertIntoBST(TreeNode root, int val) {
if (root == null){
return new TreeNode(val);
}
if (root.val > val){
root.left = insertIntoBST(root.left, val);
return root;
}
else {
root.right = insertIntoBST(root.right, val);
return root;
}
}
}
/**
* 时间复杂度 O(n)
* 空间复杂度 O(n)
*/
迭代
class Solution {
public TreeNode insertIntoBST(TreeNode root, int val) {
if (root == null){
return new TreeNode(val);
}
/**
* 插入元素需要用到父节点,因此用prev指针指向父节点
*/
TreeNode newRoot = root;
TreeNode prev = null;
while (root != null){
prev = root;
if (root.val > val){
root = root.left;
}
else {
root = root.right;
}
}
if (prev.val > val){
prev.left = new TreeNode(val);
}
else {
prev.right = new TreeNode(val);
}
return newRoot;
}
}
/**
* 时间复杂度 O(n)
* 空间复杂度 O(1)
*/
https://leetcode-cn.com/problems/insert-into-a-binary-search-tree/