144.binary-tree-preorder-traversal


144. 二叉树的前序遍历

给定一个二叉树,返回它的 前序 遍历。

 示例:

输入: [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]:
      self.traverse_path = []
      self.preorder(root)
      return self.traverse_path

    def preorder(self, root):
      if root:
        self.traverse_path.append(root.val) 
        self.preorder(root.left) 
        self.preorder(root.right)