使用递归的前/后/后顺序方法以正确的顺序返回树节点列表,而无需使用全局变量

时间:2018-11-02 19:17:16

标签: python global-variables tree-traversal

我目前正在尝试使用递归方法以in / pre / post顺序遍历时,为二叉树获取正确的节点排序。我能够使用的唯一解决方案涉及一个全局变量来保存每种遍历类型的列表。我想找到一种在不对排序列表使用全局变量的情况下获得结果的方法。

这是我的代码:

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

#GLOBAL VARIABLES
inList = []
preList = []
postList = []

#NO GLOBAL VARIABLE USED HERE
def inorder(root): 
    if root: 
        inorder(root.left) 
        print(root.val), 
        inorder(root.right) 

def postorder(root): 
    if root: 
        postorder(root.left) 
        postorder(root.right) 
        postList.append(root.val) 

    return postList

def preorder(root):
    if root: 
        preList.append(root.val) 
        preorder(root.left)  
        preorder(root.right)

    return preList

def testCase(testNumber, function, root, expectedAnswer):
    if expectedAnswer==function(root):
        print "Test", testNumber, "passed."
    else:
        print "Test", testNumber, "failed."

def test1():
    f = Node("f", [], [])
    c = Node("c", f, [])
    e = Node("e", [], [])
    g = Node("g", [], [])
    d = Node("d", [], g)
    b = Node("b", d, e)

    root = Node("a", b, c)

    testCase(1, inorder, root, ['d', 'g', 'b', 'e', 'a', 'f', 'c'])
    testCase(2, preorder, root, ['a', 'b', 'd', 'g', 'e', 'c', 'f'])
    testCase(3, postorder, root, ['g', 'd', 'e', 'b', 'f', 'c', 'a'])
    testCase(4, inorder, c, ['f','c'])
    testCase(5, preorder, e, ['e'])

2 个答案:

答案 0 :(得分:1)

您可以使用有序遍历并返回当前子树的排序列表,然后像left_subtree_result + [current_node] + right_subtree_result一样递归地加入它们。在这种情况下,由于join为O(1),因此链表的性能会更好。 (加入是指串联)

代码应为

def inorder(node):
    if node is None:
        return []
    return inorder(node.left) + [node] + inorder(node.right)

答案 1 :(得分:0)

只需传递列表以填写您的函数即可。您甚至不需要返回它,因为附加操作会原位修改列表。由于您的三个遍历几乎相同,因此我将重点介绍inorder

添加一个额外的参数:

def inorder(root, inList):
    if root: 
        inorder(root.left, inList) 
        inList.append(root.val)
        inorder(root.right, inList)

完成所有三种方法(包括删除return语句)后,可以更新testCase函数以传递本地列表:

def testCase(testNumber, function, root, expectedAnswer):
  actualAnswer = []
  function(root, actualAnswer)

  if expectedAnswer == actualAnswer:
      print "Test", testNumber, "passed."
  else:
      print "Test", testNumber, "failed."