问题描述 前序遍历。注意嵌套函数里的list应该用append而不是+=来添加元素
# 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: Optional[TreeNode]) -> List[int]:
result = []
def Preoder(root):
if root:
result.append(root.val)
Preoder(root.left)
Preoder(root.right)
Preoder(root)
return result
运行结果: