1. 程式人生 > 其它 >LeetCode | 0144. 二叉樹的前序遍歷【Python】

LeetCode | 0144. 二叉樹的前序遍歷【Python】

技術標籤:LeetCode個人題解# 二叉樹二叉樹演算法pythonleetcodedfs

Problem

LeetCode

Given the root of a binary tree, return the preorder traversal of its nodes’ values.

Example 1:

img

Input: root = [1,null,2,3]
Output: [1,2,3]

Example 2:

Input: root = []
Output: []

Example 3:

Input: root = [1]
Output: [1]

Example 4:

img

Input: root = [1,2]
Output: [1,2]

Example 5:

img

Input: root = [1,null,2]
Output: [1,2]

Constraints:

  • The number of nodes in the tree is in the range [0, 100].
  • -100 <= Node.val <= 100

Follow up:

Recursive solution is trivial, could you do it iteratively?

問題

力扣

給你二叉樹的根節點 root ,返回它節點值的 前序 遍歷。

示例 1:

img

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

示例 2:

輸入:root = []
輸出:[]

示例 3:

輸入:root = [1]
輸出:[1]

示例 4:

img

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

示例 5:

img

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

提示:

  • 樹中節點數目在範圍 [0, 100] 內
  • -100 <= Node.val <= 100

進階:遞迴演算法很簡單,你可以通過迭代演算法完成嗎?

思路

遞迴

根左右
先加入 root 節點的值,再遍歷左右子樹

Python3 程式碼

# 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 preorderTraversal(self, root: TreeNode) -> List[int]: # 遞迴 res = [] def dfs(root): if not root: return [] res.append(root.val) dfs(root.left) dfs(root.right) dfs(root) return res

迭代

使用棧來模擬

Python3 程式碼

# 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 preorderTraversal(self, root: TreeNode) -> List[int]:
        # 迭代
        res = []
        if not root:
            return res
        stack = []
        node = root
        while stack or node:
            while node:
                res.append(node.val)
                stack.append(node)
                # 前序遍歷
                node = node.left
            node = stack.pop()
            node = node.right
        return res

GitHub 連結

Python