46. Leetcode 103. 二叉树的锯齿形层序遍历 (二叉树-二叉树遍历)

给你二叉树的根节点 root ,返回其节点值的 锯齿形层序遍历 。(即先从左往右,再从右往左进行下一层遍历,以此类推,层与层之间交替进行)。

 

示例 1:


输入:root = [3,9,20,null,null,15,7]
输出:[[3],[20,9],[15,7]]
示例 2:

输入:root = [1]
输出:[[1]]
示例 3:

输入:root = []
输出:[]


# Definition for a binary tree node.
# class TreeNode:
#     def __init__(self, val=0, left=None, right=None):
#         self.val = val
#         self.left = left
#         self.right = right
class Solution:
    def zigzagLevelOrder(self, root: TreeNode) -> List[List[int]]:
        # 方法一 
        if not root:
            return []
        import collections
        queue = collections.deque()
        queue.append(root)
        index = 1
        res = []
        while queue:
            size = len(queue)
            tmp = []
            for _ in range(size):
                node = queue.popleft()
                tmp.append(node.val)
                if node.left:
                    queue.append(node.left)
                if node.right:
                    queue.append(node.right)
            
            if (index%2)==1:
                res.append(tmp)
            else:
                res.append(tmp[::-1])
            index += 1
        
        return res

        # 方法二
        if not root:
            return []
        res = []
        def dfs(root, index):
            if not root:
                return
            if len(res) < index:
                res.append(collections.deque())
            if index%2:
                res[index-1].append(root.val)
            else:
                res[index-1].appendleft(root.val)
            dfs(root.left, index + 1)
            dfs(root.right, index + 1)

        dfs(root, 1)

        return [list(q) for q in res]
        

上一篇:C++类内初始化vector 报错:expected parameter declarator


下一篇:C语言程序设计100例之(46):巧妙称重