溫馨提示×

python二叉樹遍歷代碼怎么寫

小億
87
2023-12-14 17:39:01
欄目: 編程語言

在Python中,可以使用遞歸或者迭代的方式來實現(xiàn)二叉樹的遍歷。以下是常見的三種二叉樹遍歷方式的代碼示例:

  1. 前序遍歷(Preorder Traversal):根節(jié)點 -> 左子樹 -> 右子樹

遞歸實現(xiàn):

class TreeNode:
    def __init__(self, val=0, left=None, right=None):
        self.val = val
        self.left = left
        self.right = right

def preorderTraversal(root):
    if root is None:
        return []
    result = [root.val]
    result += preorderTraversal(root.left)
    result += preorderTraversal(root.right)
    return result

迭代實現(xiàn):

def preorderTraversal(root):
    if root is None:
        return []
    stack = [root]
    result = []
    while stack:
        node = stack.pop()
        result.append(node.val)
        if node.right:
            stack.append(node.right)
        if node.left:
            stack.append(node.left)
    return result
  1. 中序遍歷(Inorder Traversal):左子樹 -> 根節(jié)點 -> 右子樹

遞歸實現(xiàn):

def inorderTraversal(root):
    if root is None:
        return []
    result = []
    result += inorderTraversal(root.left)
    result.append(root.val)
    result += inorderTraversal(root.right)
    return result

迭代實現(xiàn):

def inorderTraversal(root):
    if root is None:
        return []
    stack = []
    result = []
    while stack or root:
        if root:
            stack.append(root)
            root = root.left
        else:
            node = stack.pop()
            result.append(node.val)
            root = node.right
    return result
  1. 后序遍歷(Postorder Traversal):左子樹 -> 右子樹 -> 根節(jié)點

遞歸實現(xiàn):

def postorderTraversal(root):
    if root is None:
        return []
    result = []
    result += postorderTraversal(root.left)
    result += postorderTraversal(root.right)
    result.append(root.val)
    return result

迭代實現(xiàn):

def postorderTraversal(root):
    if root is None:
        return []
    stack = [root]
    result = []
    while stack:
        node = stack.pop()
        result.append(node.val)
        if node.left:
            stack.append(node.left)
        if node.right:
            stack.append(node.right)
    return result[::-1]

以上是常見的三種二叉樹遍歷方式的代碼示例。根據(jù)具體需求選擇合適的遍歷方式。

0