Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

iterative or recursive to implement a binary search tree?

I'm learning Data Structures & Algorithms now.

My lecture notes have an implementation of a binary search tree which is implemented using a recursive method. That is an elegant way, but my question is in real life code, should I implement a binary search tree recursively, will it generate a lot of calling stack if the tree has large height/depth number.

I understand that recursion is a key concept to understand lots of data structure concepts, but would you choose to use recursion in real life code?

like image 251
Timeless Avatar asked Jul 11 '12 15:07

Timeless


2 Answers

A tree is recursive by nature. Each node of a tree represents a subtree, and each child of each note represents a subtree of that subtree, so recursion is the best bet, especially in practice where other people people might have to edit and maintain your code.

Now, IF depth becomes a problem for your call stack, than I'm afraid that there are deeper problems with your data structure (either it's monstrously huge, or it's very unbalanced)

like image 98
Sam I am says Reinstate Monica Avatar answered Sep 28 '22 18:09

Sam I am says Reinstate Monica


"I understand that recursive is a key concept to understand lots of data structure, but will you choose to use recursive in real life code?"

After first learning about recursion I felt the same way. However, having been working in the Software industry for over a year now, I can say that I have used the concept of recursion to solve several problems. There are often times that recursion is cleaner, easier to understand/read, and just downright better. And to emphasize a point in the previous answer, a tree is a recursive data structure. IMO, there is no other way to traverse a BST :)

like image 26
Chris Dargis Avatar answered Sep 28 '22 19:09

Chris Dargis