python| #按之字形顺序打印二叉树#

按之字形顺序打印二叉树

http://www.nowcoder.com/practice/91b69814117f4e8097390d107d2efbe0

# -*- coding:utf-8 -*-
# class TreeNode:
#     def __init__(self, x):
#         self.val = x
#         self.left = None
#         self.right = None
class Solution:
    def Print(self, pRoot):
        # write code here
        if pRoot is None:
            return []
        if pRoot.left is None and pRoot.right is None:
            return [[pRoot.val]]
        result = [] #保存结果
        tem = [pRoot] #保存每一层的节点
        point = True
        while len(tem)>0:
            if point:
                tem_val = [x.val for x in tem]
                result.append(tem_val)
                tem2 = []
                for node in tem:
                    if  node.left:
                        tem2.append(node.left)
                    if  node.right:
                        tem2.append(node.right)
                point = False
                tem = tem2
            else:
                tem_val = [x.val for x in tem[::-1]]
                result.append(tem_val)
                tem2 = []
                for node in tem:
                    if  node.left:
                        tem2.append(node.left)
                    if  node.right:
                        tem2.append(node.right)
                point = True
                tem = tem2
        return result
全部评论

相关推荐

offer多多的六边形战士很无语:看了你的博客,感觉挺不错的,可以把你的访问量和粉丝数在简历里提一下,闪光点(仅个人意见)
点赞 评论 收藏
分享
点赞 评论 收藏
分享
不愿透露姓名的神秘牛友
昨天 18:54
点赞 评论 收藏
分享
点赞 收藏 评论
分享
牛客网
牛客企业服务