path to node in binary search tree as binary search tree

ZachJH :

I'm writing a binary search tree implementation, and I want to have a function that finds a node and returns a doubly linked list of all the nodes in the path it took to get there. I know that a doubly linked list can be converted to a binary search tree, so it would be really nice (and cool) to be able to use the same class.

However, if I make shallow copies of all the nodes along the way and start changing their pointers to build the binary search tree I want to return, I'll obviously be destroying the original tree. I can't just make a deep copy of all the nodes because I'll need references to the original nodes, which I'll use to change the original tree (could be deleting, balancing, ...).

For example, I might have an add function that calls find, which returns the last node in the path to where the new node would go, and I can simply place it as one of the children there. If I'm writing a self-balancing binary tree class (Red/Black Tree, AVL Tree, Splay Tree), which I can subclass off this one, it will be nice to have access to at least the parent and grandparent of the node I just added (which I could just track with extra pointers, but then the find method isn't as versatile).

Of course, one solution is to just write another class. Another solution would be to settle for a singly-linked list, and use the other pointer to refer back to the corresponding original node. But, at this point, it's about more than just having a solution that works. The language I'm using is Java, but I'd definitely be interested in knowing if any other language has some feature for this, as well. It doesn't seem very possible to me, but I could totally be missing something.

Does anyone know if there's a way to do this, or have any suggestions for what I might do instead?

Daniel Junglas :

So you want to use the node class used for the binary tree to build a double linked list. I assume that this node class has four fields: leffChild, rightChild, parent, data, where data holds the data stored at the node. Now you can misuse these fields to create a doubly-linked list, for example by using leftChild as prev and rightChild as next field of the node in the doubly-linked list. If you do so then you can still use the parent and data fields of that node. So you can create new nodes for the doubly linked list but have the parent field of those nodes point to the respective node in the binary tree.

This being said, your approach sounds a bit strange. The nodes in the doubly-linked list will have one unused field. Moreover, Java provides java.util.LinkedList which implements a doubly linked list. So there is no need to roll your own by obfuscated use of binary tree nodes.

Guess you like

Origin http://43.154.161.224:23101/article/api/json?id=335384&siteId=1