Insert into a Binary Search Tree
Last updated
Last updated
Given the root of a BST and new value, insert the new value into the BST.
Assume no duplicated values.
Traversing the tree then at the base adding the new node is an intuitive solution.
Dividing on just one side and merge that one side.
Which one is better?
DFS (pre-order traversal) is a little faster in this case because it only has to change the reference of one leaf node. But the time complexity is the same for both at O(h).
D&C is a lot cleaner to write. This problem requires a special case at the parent level. D&C can handle that a lot nicer.
Is D&C always a better option?
Traversal only has access to the current node (parent node info has to get passed down). And it can return stuff to the top level.
D&C has access to the child subtrees because of backtracking.
It is clearly the better option when
Want to modify at the parent node level (this problem)
It is a stylistic choice when
It is not preferred when the solution has to be implemented iteratively
Conclusion
When the choice of a design pattern or algorithmic pattern is clear, a clean solution should follow, even when the mind is lack of creativity.
Need information from both subtrees ()
The problem can defined recursively but can also be solved with a global value / log ()