简体   繁体   English

叶到根bst遍历

[英]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? 我只是想知道,给定一个指向其左右子节点的节点,是否有可能以某种方式获得整个bst树的有序打印?

All i know about the tree is that it is BST. 我只知道这棵树是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)

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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