1

I've implemented a binary search tree in Java that can search for a particular node. After I find a particular node, I'd also like to retrieve a particular number of nodes (say, 5) that are ordered before the node found. The only way I can think of to achieve this is: Traverse through the entire tree, add each node to an arraylist (or another flat data structure), and then find the node in the arraylist and retrieve the five previous nodes.

But this is inefficient and inelegant. Is there a way to do this just by traversing through the tree, backwards?

  • Surely the last-visited are just the parents of the node in question? – Oliver Charlesworth May 24 '14 at 13:09
  • @OliCharlesworth Not necessarily. – HelloWorld123456789 May 24 '14 at 13:12
  • @RikayanBandyopadhyay: If not, then what exactly does the OP mean by "last visited"? – Oliver Charlesworth May 24 '14 at 13:12
  • Oops sorry should clarify, I meant the few nodes that are before the node that is found, in order. Eg, if I wanted to find 6 in a tree with numbers 1 to 10, the previous 3 nodes are 3,4,5. –  May 24 '14 at 13:13
  • @OliCharlesworth Does the last 5 visited nodes always have to be the parents of the current node in a bst?! – HelloWorld123456789 May 24 '14 at 13:14
  • @Mal: I don't understand that example. Why would you necessarily have visited 3,4,5 to get to 6? Can you add some ASCII art (or something) to your question to illustrate what you are asking? – Oliver Charlesworth May 24 '14 at 13:15
  • @Mal I don't think storing the last 5 nodes is inefficient in any sense. Adding/deleting from that list can be done in O(1) time. And space also remains constant. What is your purpose? Can you elaborate on that? – HelloWorld123456789 May 24 '14 at 13:17
  • Hmm ok not necessarily visited, just the nodes that are lexicographically before the node found in the tree. –  May 24 '14 at 13:19
  • 2
    @Mal: Oh, well that's a completely different problem! You should rewrite your question accordingly... – Oliver Charlesworth May 24 '14 at 13:20
  • Sounds like you want a [threaded binary tree](http://en.wikipedia.org/wiki/Threaded_binary_tree). – Oliver Charlesworth May 24 '14 at 13:27
  • I think finding the the predecessor is a bit harder, but it looks like a threaded binary tree would solve the problem! Thanks @OliCharlesworth :D –  May 24 '14 at 13:44
  • 1
    Finding the predecessor is identical to finding the successor, you just replace every occurrence of "left" with "right" and vice versa in the algorithm. – Bernhard Barker May 24 '14 at 15:18
  • I see now, thanks @Dukeling! I guess my problem was more to do with knowing what I actually wanted to do, and what to search to solve the problem. –  May 25 '14 at 03:57

0 Answers0