题解 | #实现二叉树先序,中序和后序遍历#
实现二叉树先序,中序和后序遍历
http://www.nowcoder.com/practice/a9fec6c46a684ad5a3abd4e365a9d362
递归
# class TreeNode:
# def __init__(self, x):
# self.val = x
# self.left = None
# self.right = None
#
# 代码中的类名、方法名、参数名已经指定,请勿修改,直接返回方法规定的值即可
#
#
# @param root TreeNode类 the root of binary tree
# @return int整型二维数组
#
class Solution:
def threeOrders(self , root: TreeNode) -> List[List[int]]:
# write code here
return [self.front(root), self.middle(root), self.back(root)]
def front(self, root, var=None):
if root is None:
return # 终止递归
if var is None:
var = [] # 开始递归,初始化结果存储列表
var.append(root.val)
lt = self.front(root.left, var)
rt = self.front(root.right, var)
return var
def middle(self, root, var=None):
if root is None:
return
if var is None:
var = []
lt = self.middle(root.left, var)
var.append(root.val)
rt = self.middle(root.right, var)
return var
def back(self, root, var=None):
if root is None:
return
if var is None:
var = []
lt = self.back(root.left, var)
rt = self.back(root.right, var)
var.append(root.val)
return var