简体   繁体   中英

leaf to root bst traversal

I was just wondering, given a node which points to its left and right children, is it possible to somehow get an inorder print of the whole bst tree?

All i know about the tree is that it is BST. And all I know about the node is that he knows who his children are (left and right). I don't have access to neither the root nor the father of the node. The node chosen is picked randomly, and I need to return an inorder of the whole tree.

I think there is not enough info to get started at, and my friend got this question during a job interview, and was wondering if that was an unsolvable question or is there a trick I don't know about?

Thanks in advance for any help :)

The only thing you can do from this situation is to travel downwards, because you have no pointer to the parent node. The only case when you can print the whole tree is when the node considered is the root.

So, you can get the inorder print of the subtree rooted at the current node. If this node is the root, then it prints the whole tree. If it is not, then it does not.

Just in case, inorder print is simple:

def inorder(node):
    if node == null: return
    inorder(node.left)
    print node.data
    inorder(node.right)

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM