给定一个二叉树,返回它的 前序 遍历。
示例:
输入: [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):
"""
:type root: TreeNode
:rtype: List[int]
"""
def dummy(root,l):
if not root:
return
result.append(root.val)
if root.left:
dummy(root.left,result)
if root.right:
dummy(root.right,result)
result=[]
dummy(root,result)
return result
执行用时: 44 ms, 在Binary Tree Preorder Traversal的Python3提交中击败了98.03% 的用户
给定一个二叉树,返回它的 后序 遍历。
示例:
输入: [1,null,2,3] 1 \ 2 / 3 输出: [3,2,1]
# Definition for a binary tree node.
# class TreeNode:
# def __init__(self, x):
# self.val = x
# self.left = None
# self.right = None
class Solution:
def postorderTraversal(self, root):
"""
:type root: TreeNode
:rtype: List[int]
"""
def dummy(root,l):
if not root:
return
if root.left:
dummy(root.left,result)
if root.right:
dummy(root.right,result)
result.append(root.val)
result=[]
dummy(root,result)
return result
执行用时: 44 ms, 在Binary Tree Postorder Traversal的Python3提交中击败了97.88% 的用户