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

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

?著作權歸作者所有,轉載或內容合作請聯系作者
平臺聲明:文章內容(如有圖片或視頻亦包括在內)由作者上傳并發布,文章內容僅代表作者本人觀點,簡書系信息發布平臺,僅提供信息存儲服務。

推薦閱讀更多精彩內容