题解 | 实现二叉树先序,中序和后序遍历 | 直接三次递归

实现二叉树先序,中序和后序遍历

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 ):
        # write code here
        def pre(root,res):
            if not root:
                return
            res.append(root.val)
            pre(root.left,res)
            pre(root.right,res)
            
        
        def inner(root,res):
            if not root:
                return
            inner(root.left, res)
            res.append(root.val)
            inner(root.right, res)
            
        def after(root,res):
            if not root:
                return
            after(root.left, res)
            after(root.right, res)
            res.append(root.val)
            
        res=[]
        a,b,c=[],[],[]
        pre(root, a)
        inner(root, b)
        after(root, c)
        res.extend([a,b,c])
        return res
全部评论

相关推荐

01-24 12:50
门头沟学院 C++
投票
菜狗二号:还有啥想的 指定国有行啊,去了就开始幸福美满的生活了,选华子不是折腾自己么,最终财富积累度是差不多的,但是幸福指数是相差甚远的
点赞 评论 收藏
分享
评论
1
收藏
分享

创作者周榜

更多
牛客网
牛客企业服务