简体   繁体   English

中序二叉树遍历(使用 Python)

[英]Inorder Binary Tree Traversal (using Python)

I am trying to perform an inorder traversal of a tree.我正在尝试对树进行中序遍历。 The code itself feels right, except it is not working properly.代码本身感觉是正确的,只是它不能正常工作。 I have a feeling it has to either do with the if condition, how append works in python, or something perhaps with return.我有一种感觉,它要么与 if 条件有关,也与 append 在 python 中的工作方式有关,或者与返回有关。 This works correctly if I use print instead of return, I think, but I want to be able to use return and still get the correct answer.如果我使用打印而不是返回,这可以正常工作,我想,但我希望能够使用返回并仍然得到正确的答案。 For example, for the tree [1,None,2,3], my code returns [1] which is clearly incorrect.例如,对于树 [1,None,2,3],我的代码返回 [1],这显然是不正确的。

Additionally is it possible to solve this problem using list comprehension?另外是否可以使用列表理解来解决这个问题? If so, any sample code would be greatly appreciated.如果是这样,任何示例代码将不胜感激。

Here is my code:这是我的代码:

    class Solution(object):
        def inorderTraversal(self, root):
            res = []
            if root:
                self.inorderTraversal(root.left)
                res.append(root.val)
                self.inorderTraversal(root.right)
            return res

Also before marking this as a duplicate, I know in order traversals have been asked on Stackoverflow (plenty of times), but none of them helped me understand why my understanding is wrong.同样在将其标记为重复之前,我知道在 Stackoverflow 上按顺序询问了遍历(很多次),但没有一个帮助我理解为什么我的理解是错误的。 I would be so grateful if someone helped me learn how to correct my approach versus simply posting another link without explanation.如果有人帮助我学习如何纠正我的方法,而不是简单地发布另一个链接而无需解释,我将不胜感激。 Thank you so much!非常感谢!

The reason this doesn't work is that res only has the value of the first node you give it appended to it; 这不起作用的原因是res只有你给它附加的第一个节点的值; each time you recursively recall the function, it just makes a new res. 每次递归调用该函数时,它只会生成一个新的res。 It is a simple fix though, as follows: 这是一个简单的修复,如下:

class Solution(object):
    def inorderTraversal(self, root):
        res = []
        if root:
            res = self.inorderTraversal(root.left) 
            res.append(root.val)
            res = res + self.inorderTraversal(root.right)
        return res

In this, it returns the left branch, the value, and then the right. 在此,它返回左分支,值,然后返回右。 This can be done much more briefly as follows: 这可以简单地做到如下:

class Solution(object):
    def inorderTraversal(self, root):
        return (self.inorderTraversal(root.left) + [root.val] + self.inorderTraversal(root.right)) if root else []

Use this instead , a simple recursion :: 使用这个,一个简单的递归::

class Node:
    def __init__(self,key):
        self.left = None
        self.right = None
        self.val = key

def printInorder(root):
    if root:
        printInorder(root.left)
        print(root.val)
        printInorder(root.right)

def printPostorder(root):
    if root:
        printPostorder(root.left)
        printPostorder(root.right)
        print(root.val)

def printPreorder(root):
    if root:
        print(root.val)
        printPreorder(root.left)
        printPreorder(root.right)

# Driver code
root = Node(1)
root.left      = Node(2)
root.right     = Node(3)
root.left.left  = Node(4)
root.left.right  = Node(5)
print "Preorder traversal of binary tree is"
printPreorder(root)

print "\nInorder traversal of binary tree is"
printInorder(root)

print "\nPostorder traversal of binary tree is"
printPostorder(root)

Source :: here 来源:: 这里

@Benedict Randall Shaw's answer is already perfect. @Benedict Randall Shaw 的回答已经很完美了。 I just want to add some fun to it in a pythonic way.我只是想以 Pythonic 的方式为它添加一些乐趣。 Although the doc does not suggest using a mutable object as default parameter, this will somewhat simplify the code by treating the default mutable list as a class member of the python function.尽管文档不建议使用可变对象作为默认参数,但通过将默认可变list视为 python 函数的类成员,这将在一定程度上简化代码。

The difference is only the += is replaced by = , since the res is always the same list object inside the function before the function object is garbage collected.所不同的是只+=被替换= ,由于res始终是相同的list在函数内部对象之前的功能对象是垃圾收集。

def inorderTraversal(root, res=[]):
    if root:
        res = inorderTraversal(root.left)
        res.append(root.val)
        res = inorderTraversal(root.right)
return res

Yet another approach to output a list, the advantage being that you need to add values only to a single list:输出列表的另一种方法,优点是您只需将值添加到单个列表:

def inorder(root):
    return_list = []
    def innerInOrder(root):
        if root == None:
          return
        innnerInOrder(root.left)
        return_list.append(root.data)
        innerInOrder(root.right)
    innerInOrder(root)
    return return_list

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

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