1. 程式人生 > 其它 >LeetCode 20 Valid Parentheses 括號匹配

LeetCode 20 Valid Parentheses 括號匹配

技術標籤:演算法python二叉樹leetcode演算法python

LC 二叉樹的前序遍歷

題目

題目連結

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

示例 1:
在這裡插入圖片描述

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

示例 2:

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

示例 3:

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

示例 4:
在這裡插入圖片描述

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

示例 5:

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

在這裡插入圖片描述

解題

方法一:遞迴

# 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]: def preorder(root: TreeNode): if not root: return
res.append(root.val) preorder(root.left) preorder(root.right) res = list() preorder(root) return res

方法二:迭代

模板解法:

# 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]: if not root: return [] cur=root res=[] stack=[] while stack or cur: while cur: res.append(cur.val) stack.append(cur) cur = cur.left cur = stack.pop() cur = cur.right return res

常規解法:

class Solution:
    def preorderTraversal(self, root: TreeNode) -> List[int]:
        ans = []
        if not root:
            return ans
        stack = [root]
        while stack:
            node = stack.pop()
            ans.append(node.val)
            if node.right:
                stack.append(node.right)
            if node.left:
                stack.append(node.left)
        return ans