144. Binary Tree Preorder Traversal
知识点:stack
1.原题
Given a binary tree, return the preorder traversal of its nodes’ values.
Example:
Input: [1,null,2,3]
1
\
2
/
3
Output: [1,2,3]
Follow up: Recursive solution is trivial, could you do it iteratively?
2. 题意
进行先序遍历,即:根左右
3. 思路
我首先是按照103. Binary Tree Zigzag Level Order Traversal的思路来做的,新 def 一个函数,然后在那个函数里对自身进行调用,将root改为 root.left 和 root.right ,在主函数中只需要将root和an传入即可,但是这个solution是time excess了,所以我也不知道是不是能行得通。所以我就在主函数中直接进行调用,对root是append,对left和right是extend。
4. 代码
# Definition for a binary tree node.
# class TreeNode(object):
# def __init__(self, x):
# self.val = x
# self.left = None
# self.right = None
class Solution(object):
def preorderTraversal(self, root):
"""
:type root: TreeNode
:rtype: List[int]
"""
an=[]
if root:
an.append(root.val)
an.extend(self.preorderTraversal(root.left))
an.extend(self.preorderTraversal(root.right))
else:
return []
return an
5. Reference
https://blog.csdn.net/fuxuemingzhu/article/details/72575422