tutorialcup
Insert into a Binary Search Tree Leetcode Solution
In this problem, we are given the root node of a Binary Search Tree containing integer values and an integer value of a node that we have to add in the Binary Search Tree and return its structure. After inserting the element into the BST, we have to print its Inorder Traversal.
Example
Binary Search Tree:
7
/
3 10
/
8
Integer Value = 11
3 7 8 10 11
Binary Search Tree:
5
/
4
/
3
Integer Value = 2
2 3 4 5
Explanation
Approach(Recursive)
In order to decide where should any given node be inserted in our Binary Search Tree, we must set up a path from the root to the corresponding node whose left/right child will be the given node.
We can solve this recursively by passing on the task from a problem to its sub-problem. In this case, inserting a new node into a tree means to insert it to either its left subtree or right subtree. The same idea also holds for any further subtrees. We need to set up a base case. When we reach a point where the root node of any subtree is NULL, it would mean that we have reached the end of the path to insert the target node. So, we return a new node address having node value as the given value. Binary Search Trees have a significant advantage to search for any arbitrary element in O(logN) time under average cases. So, in this case, we find the position of the new node to be inserted in efficient time.
Algorithm
www.tutorialcup.com/leetcode-solutions/insert-into-a-bina...
Insert into a Binary Search Tree Leetcode Solution
In this problem, we are given the root node of a Binary Search Tree containing integer values and an integer value of a node that we have to add in the Binary Search Tree and return its structure. After inserting the element into the BST, we have to print its Inorder Traversal.
Example
Binary Search Tree:
7
/
3 10
/
8
Integer Value = 11
3 7 8 10 11
Binary Search Tree:
5
/
4
/
3
Integer Value = 2
2 3 4 5
Explanation
Approach(Recursive)
In order to decide where should any given node be inserted in our Binary Search Tree, we must set up a path from the root to the corresponding node whose left/right child will be the given node.
We can solve this recursively by passing on the task from a problem to its sub-problem. In this case, inserting a new node into a tree means to insert it to either its left subtree or right subtree. The same idea also holds for any further subtrees. We need to set up a base case. When we reach a point where the root node of any subtree is NULL, it would mean that we have reached the end of the path to insert the target node. So, we return a new node address having node value as the given value. Binary Search Trees have a significant advantage to search for any arbitrary element in O(logN) time under average cases. So, in this case, we find the position of the new node to be inserted in efficient time.
Algorithm
www.tutorialcup.com/leetcode-solutions/insert-into-a-bina...