LeetCode 103.二叉树的锯齿形层次遍历

二叉树的层次遍历代码:

# Definition for a binary tree node.
# class TreeNode:
#     def __init__(self, x):
#         self.val = x
#         self.left = None
#         self.right = None

def levelOrder(self, root: TreeNode) -> List[List[int]]:
    if not root:                 # root为空时直接返回[]
        return []
    res = []                     # 返回的最终结果
    cur_nodes = [root]           # 当前访问层
    next_nodes = []              # 下一层需要访问的
    res.append([i.val for i in cur_nodes])     # 先把第一层的值放入res中
    while cur_nodes or next_nodes:    # 当前结点或下一层结点不为空
        for node in cur_nodes:        # 当前结点的所有孩子都加入next_nodes
            if node.left:
                next_nodes.append(node.left)
            if node.right:
                next_nodes.append(node.right)
        # 下一层结点不为空时加入res
        if next_nodes:
            res.append(
                [i.val for i in next_nodes]
            )
        cur_nodes = next_nodes  # 更新当前结点为next_nodes
        next_nodes = []  # 下一层结点置空
    return res

我的思路:

设置一个flag 

对奇数层采取和普通层次遍历相同的顺序 

对偶数层采取和普通层次遍历相反的顺序

res不变  ans用来存放满足题目要求的输出

我的代码:

def zigzagLevelOrder(self, root):
        # root为空时直接返回[]
        if not root:                 
            return []
        flag=1
        res = []   
        ans=[]               
        cur_nodes = [root]           # 当前访问层
        next_nodes = []              # 下一层需要访问的
        res.append([i.val for i in cur_nodes])     # 先把第一层的值放入res和ans中
        ans.append([i.val for i in cur_nodes]) 
        while cur_nodes or next_nodes:    # 当前结点或下一层结点不为空
            for node in cur_nodes:        # 当前结点的所有孩子都加入next_nodes
                if node.left:
                    next_nodes.append(node.left)
                if node.right:
                    next_nodes.append(node.right)
            if next_nodes:                # 下一层结点不为空时加入res
                res.append(
                    [i.val for i in next_nodes]
                )
            # 判断是奇数层还是偶数层
            if flag%2==1:
                tmp=next_nodes[::-1]
            else:
                tmp=next_nodes
            flag+=1
            # 将节点加入ans
            if tmp:                
                ans.append(
                    [i.val for i in tmp]
                )
            cur_nodes = next_nodes  # 更新当前结点为next_nodes
            next_nodes = []  # 下一层结点置空
        return ans

 

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值