Problem
Given the root of a binary tree, return the preorder traversal of its nodes’ values.
Algorithm
dfs.
Code
# 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]:
if not root:
return []
ans = []
def dfs(proot):
if not proot:
return
ans.append(proot.val)
dfs(proot.left)
dfs(proot.right)
dfs(root)
return ans