46 lines
1.0 KiB
Python
46 lines
1.0 KiB
Python
#
|
|
# @lc app=leetcode.cn id=144 lang=python3
|
|
#
|
|
# [144] 二叉树的前序遍历
|
|
#
|
|
|
|
# @lc code=start
|
|
# 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
|
|
from typing import List
|
|
|
|
from utils import *
|
|
|
|
|
|
class Solution:
|
|
def preorderTraversal(self, root: TreeNode) -> List[int]:
|
|
res = []
|
|
stack = []
|
|
if root:
|
|
stack.append(root)
|
|
while stack:
|
|
node = stack[-1]
|
|
if node:
|
|
stack.pop()
|
|
if node.right:
|
|
stack.append(node.right)
|
|
if node.left:
|
|
stack.append(node.left)
|
|
stack.append(node)
|
|
stack.append(None)
|
|
else:
|
|
stack.pop()
|
|
node = stack.pop()
|
|
res.append(node.val)
|
|
return res
|
|
|
|
|
|
s = Solution()
|
|
root = generate_tree([1, None, 2])
|
|
s.preorderTraversal(root)
|
|
# @lc code=end
|