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

按之字形顺序打印二叉树

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
        res_temp = []
        res = []
        if not pRoot:
            return res
        stack = []
        next_s = []
        stack.append(pRoot)
        flag = 1
        while stack:
            res_temp = []
            for item in stack:
                res_temp.append(item.val)
                if item.left:
                    next_s.append(item.left)
                if item.right:
                    next_s.append(item.right)
            res.append(res_temp[::flag])
            flag*=-1
            stack = next_s
            next_s = []
        return res
全部评论

相关推荐

头像
2025-12-23 12:56
英特尔_Software_engineer
点赞 评论 收藏
分享
评论
点赞
收藏
分享

创作者周榜

更多
牛客网
牛客网在线编程
牛客网题解
牛客企业服务