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.
1#include <iostream>
2using namespace std;
3
4struct TreeNode {
5 int val;
6 TreeNode *left, *right;
7 TreeNode(int x) : val(x), left(NULL), right(NULL) {}
8};
9
10TreeNode* insertIntoBST(TreeNode* root, int val) {
11 TreeNode* node = new TreeNode(val);
12 if (!root) return node;
13 TreeNode* curr = root;
14 while (curr) {
15 if (val < curr->val) {
16 if (!curr->left) {
17 curr->left = node;
18 break;
19 }
20 curr = curr->left;
21 } else {
22 if (!curr->right) {
23 curr->right = node;
24 break;
25 }
26 curr = curr->right;
27 }
28 }
29 return root;
30}
This iterative solution creates a new node and then traverses the binary search tree to find the correct position without recursion. It places the new node in the proper location based on its value maintaining the BST properties.
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.
1
This recursive Java solution effectively traverses the BST by comparing node values to position the new node appropriately within the binary search tree properties.