簡體   English   中英

樹的有序遍歷

[英]inorder traversal of tree

我正在查看樹實現的有序遞歸遍歷,並且想知道如何將結果保存到列表中並從遞歸函數中返回。 我在堆棧展開期間如何保留此列表時遇到問題。

因此,我的代碼為:

class BinaryTreeNode(object):
    def __init__(self, value):
        self.value = value
        self.left = None
        self.right = None

def recursive_inorder(root):
    if not root:
        return

    nodes = list()

    recursive_inorder(root.left)
    nodes.append(root.value)
    print root.value
    recursive_inorder(root.right)
    return nodes

我稱之為:

three = BinaryTreeNode(3)
five = BinaryTreeNode(5)
one = BinaryTreeNode(1)
four = BinaryTreeNode(4)
two = BinaryTreeNode(2)
six = BinaryTreeNode(6)

three.left = five
five.left = one
five.right = four

three.right = two
two.left = six

nodes = recursive_inorder(three)

節點以正確的順序遍歷,但是我很難弄清楚如何將結果保存到nodes列表中。

使用遞歸調用的返回值擴展節點列表。 另外,當您具有None值時,返回一個空列表,因此可以保證函數始終返回一個列表:

def recursive_inorder(root):
    if not root:
        return []

    nodes = list()

    nodes.extend(recursive_inorder(root.left))
    nodes.append(root.value)
    nodes.extend(recursive_inorder(root.right))
    return nodes

或更簡潔:

def recursive_inorder(root):
    if not root:
        return []

    return recursive_inorder(root.left) + [root.value] + recursive_inorder(root.right)

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM