最后更新于
最后更新于
输入: [1,null,2,3]
1
\
2
/
3
输出: [1,2,3]
# Definition for a binary tree node.
# class TreeNode:
# def __init__(self, x):
# self.val = x
# self.left = None
# self.right = None
class Solution:
def preorderTraversal(self, root: TreeNode) -> List[int]:
res = []
def dfs(node):
if node is None:
return
res.append(node.val)
dfs(node.left)
dfs(node.right)
dfs(root)
return res
class Solution:
def preorderTraversal(self, root: TreeNode) -> List[int]:
if root is None:
return []
res, stack = [], [root]
while stack:
node = stack.pop(-1)
res.append(node.val)
if node.right is not None:
stack.append(node.right)
if node.left is not None:
stack.append(node.left)
return res