题目
Given the root of a binary tree, return the preorder traversal of its nodes’ values.
解题思路
递归和非递归两种方法
代码
class Solution:
def preorderTraversal(self, root: Optional[TreeNode]) -> List[int]:
if not root:
return []
return [root.val] + self.preorderTraversal(root.left) + self.preorderTraversal(root.right)
class Solution:
def preorderTraversal(self, root: Optional[TreeNode]) -> List[int]:
stack, res = [root], []
while stack:
cur = stack.pop()
if cur:
res.append(cur.val)
stack.append(cur.right)
stack.append(cur.left)
return res