天天看點

*python3__leecode/0094.二叉樹的中序周遊一、刷題内容二、解題方法

94. binary tree inordertraversal二叉樹的中序周遊

  • 一、刷題内容
    • 原題連結
    • 内容描述
  • 二、解題方法
    • 1.方法一:遞歸
    • 2.方法二:疊代
    • 3.方法三:顔色标記

一、刷題内容

原題連結

https://leetcode-cn.com/problems/binary-tree-inorder-traversal/

内容描述

給定一個二叉樹的根節點 root ,傳回它的 中序 周遊。

示例 1:

輸入:root = [1,null,2,3]

輸出:[1,3,2]

示例 2:

輸入:root = []

輸出:[]

示例 3:

輸入:root = [1]

輸出:[1]

示例 4:

輸入:root = [1,2]

輸出:[2,1]

示例 5:

輸入:root = [1,null,2]

輸出:[1,2]

提示:

樹中節點數目在範圍 [0, 100] 内

-100 <= Node.val <= 100

二、解題方法

1.方法一:遞歸

# Definition for a binary tree node.
# class TreeNode:
#     def __init__(self, val=0, left=None, right=None):
#         self.val = val
#         self.left = left
#         self.right = right
class Solution:
    def inorderTraversal(self, root: TreeNode) -> List[int]:
        if not root:
            return []
        return self.inorderTraversal(root.left)+ [root.val] + self.inorderTraversal(root.right)
           

2.方法二:疊代

class Solution:
    def inorderTraversal(self, root: TreeNode) -> List[int]:
        res = []
        stack = []
        while stack or root:
        # 不斷往左子樹方向走,每走一次就将目前節點儲存到棧中
        # 這是模拟遞歸的調用
            if root:
                stack.append(root)
                root = root.left
        # 目前節點為空,說明左邊走到頭了,從棧中彈出節點并儲存
        # 然後轉向右邊節點,繼續上面整個過程
            else:
                tmp = stack.pop()
                res.append(tmp.val)
                root = tmp.right
        return res
           

3.方法三:顔色标記

class Solution:
    def inorderTraversal(self, root: TreeNode) -> List[int]:
        WHITE, GRAY = 0, 1
        res = []
        stack = [(WHITE, root)]
        while stack:
            color, node = stack.pop()
            if node is None:
                continue
            if color == WHITE:
                stack.append((WHITE, node.right))
                stack.append((GRAY, node))
                stack.append((WHITE, node.left))
            else:
                res.append(node.val)
        return res