Sponsored
Sponsored
In this approach, we start from the root and traverse the tree to find an appropriate place for the new node without recursion. At each step, we decide to move left or right depending on the value of the node compared to the value we want to insert. Once we find a suitable spot, we insert the new node as a leaf and return.
Time Complexity: O(h) where h is the height of the tree. Space Complexity: O(1) since no extra space is utilized.
1class TreeNode {
2 int val;
3 TreeNode left, right;
4 TreeNode(int x) { val = x; }
5}
6
7class Solution {
8 public TreeNode insertIntoBST(TreeNode root, int val) {
9 TreeNode node = new TreeNode(val);
10 if (root == null) return node;
11 TreeNode curr = root;
12 while (true) {
13 if (val < curr.val) {
14 if (curr.left == null) {
15 curr.left = node;
16 break;
17 } else {
18 curr = curr.left;
19 }
20 } else {
21 if (curr.right == null) {
22 curr.right = node;
23 break;
24 } else {
25 curr = curr.right;
26 }
27 }
28 }
29 return root;
30 }
31}
This Java solution iteratively finds the right location in the BST for the new value and inserts it as a leaf. No recursion is used, making it simpler for deeper trees with lesser stack overhead.
In the recursive method, we start at the root and recursively call the function for either the left or right subtree, based on comparisons, until an appropriate leaf is found for insertion. This method utilizes the call stack to keep track of previous nodes.
Time Complexity: O(h), where h is the height of the tree.
Space Complexity: O(h), due to the recursive stack space.
1using namespace std;
struct TreeNode {
int val;
TreeNode *left, *right;
TreeNode(int x) : val(x), left(nullptr), right(nullptr) {}
};
TreeNode* insertIntoBST(TreeNode* root, int val) {
if (!root) return new TreeNode(val);
if (val < root->val)
root->left = insertIntoBST(root->left, val);
else
root->right = insertIntoBST(root->right, val);
return root;
}
In this C++ recursive solution, the function inserts a new node into the tree by exploring either the left or right subtrees based on comparisons until a suitable spot is found.