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

按之字形顺序打印二叉树

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

# class TreeNode:
#     def __init__(self, x):
#         self.val = x
#         self.left = None
#         self.right = None
#
# 代码中的类名、方法名、参数名已经指定,请勿修改,直接返回方法规定的值即可
#
#
# @param pRoot TreeNode类
# @return int整型二维数组
#
# 每一层需要判断当前是奇数层还是偶数层,偶数层保存的结果要逆序
class Solution:
    def Print(self, pRoot: TreeNode) -> List[List[int]]:
        if not pRoot:
            return None

        flag = True
        ans = []
        cur = [pRoot]
        nex = []

        while cur:
            temp = []
            for node in cur:
                temp.append(node.val)
                if node.left:
                    nex.append(node.left)
                if node.right:
                    nex.append(node.right)
            
            if flag:
                ans.append(temp)
            else:
                ans.append(temp[::-1])
            flag = not flag
            cur = nex
            nex = []

        return ans

全部评论

相关推荐

牛油果甜奶昔:别的先不说,牛客还能内推护士?
点赞 评论 收藏
分享
Hyh_111:像这种hr就不用管了,基本没啥实力,换一个吧
点赞 评论 收藏
分享
评论
点赞
收藏
分享

创作者周榜

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