简体   繁体   English

Python中树的中序遍历返回一个列表

[英]Inorder Traversal of Tree in Python Returning a List

I learnt implementing inorder traversal of a binary search tree:我学会了实现二叉搜索树的中序遍历:

def inorder(root): # root has val, left and right fields
    if root==None:
        return

    inorder(root.left)
    print(root.val)
    inorder(root.right)

Now, the problem is I do not want console output.现在,问题是我不想要控制台输出。 I want to get the values in a list.我想获取列表中的值。 I can't find a way to make the function return a list.我找不到让函数返回列表的方法。

I tried s = [inorder(root)] but it doesn't work.我试过s = [inorder(root)]但它不起作用。

So, my question is:所以,我的问题是:

  1. Any way this could be done inside the inorder function, ie it should return a list rather than just print values.任何方式都可以在 inorder 函数内完成,即它应该返回一个列表而不仅仅是打印值。

  2. Is there some generic way to make recusive functions return data structures instead of just outputting a print to console?是否有一些通用方法可以使递归函数返回数据结构,而不仅仅是将打印输出到控制台?

You can build up the list recursivly.您可以递归地构建列表。 Simply add the returned list from the left and right trees together with the value in the current node.只需将左右树返回的列表与当前节点中的值相加即可。

def inorder(root):
    if root==None:
        return []

    left_list = inorder(root.left)
    right_list = inorder(root.right)
    return left_list + [val] + right_list 

You can pass a list, and then append the values to it, like this-您可以传递一个列表,然后将值附加到它,就像这样 -

def inorder(root,ans): # root has val, left and right fields
    if root==None:
        return

    inorder(root.left)
    ans.append(root.val)
    inorder(root.right)
ans=[]
inorder(root,ans)
print(ans)

Answering your second query :回答您的第二个查询

Passing the data structure itself is the simplest solution.传递数据结构本身是最简单的解决方案。 If you really want the function to "return" the output, One way is using list concatenation as @Shaido suggested, but it is slightly heavier on memory by unnecessarily creating a new singleton list at every recursive call.如果您真的希望函数“返回”输出,一种方法是使用@Shaido 建议的列表连接,但通过在每次递归调用时不必要地创建一个新的单例列表,它会稍微占用内存。

A better solution would be using some static list(ie a fixed list that would be declared only once).更好的解决方案是使用一些静态列表(即只声明一次的固定列表)。 But it's not available directly in python, because python suggests doing it by declaring it inside a class.但它不能直接在 python 中使用,因为 python 建议通过在类中声明它来实现。 ( A good discussion here ) 这里有一个很好的讨论

def inorder(root, arr):

    if root is None:
        return
    arr.append(root.val)
    traverse(root.left, arr)
    traverse(root.right,arr)
    return arr


inorder_list = inorder(root, [])

Happy Coding :)快乐编码:)

I was having similar issue like yours a while ago.前段时间我遇到了和你一样的问题。 A workaround that I came up with was to create a utility function where you pass a list.我想出的一种解决方法是创建一个实用程序函数,您可以在其中传递一个列表。 This list will be filled by the time the recursion is done.该列表将在递归完成时填充。

Now, in your main function, you simply invoke the utility function with your root node and an empty list as your parameters.现在,在您的主函数中,您只需使用根节点和一个空列表作为参数调用实用程序函数。 I hope that was helpful.我希望那是有帮助的。 Cheers!干杯!

def preorderTraversal(self, root: TreeNode) -> List[int]:
        result = []
        self.preorder(root, result)       
        return result
    
def preorder(self, node, arr):
        if not node:
            return
        arr.append(node.val)
        self.preorder(node.left, arr)
        self.preorder(node.right, arr)

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

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