leetcode/144.二叉树的前序遍历.py
Ching 0ea07fca4c feat(leetcode;): 144.二叉树的前序遍历
144.二叉树的前序遍历

Signed-off-by: Ching <loooching@gmail.com>
2022-01-23 16:23:32 +08:00

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