Skip to the content.

leetcode [103] 二叉树的锯齿形层次遍历


Contact me:

Blog -> https://cugtyt.github.io/blog/index
Email -> cugtyt@qq.com
GitHub -> Cugtyt@GitHub


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

例如:

给定二叉树 [3,9,20,null,null,15,7],

    3
   / \
  9  20
    /  \
   15   7
返回锯齿形层次遍历如下:

[
  [3],
  [20,9],
  [15,7]
]
class Solution:
    def zigzagLevelOrder(self, root: TreeNode) -> List[List[int]]:
        if not root:
            return []
        ans = []
        level = [root]
        while level:
            newlevel = []
            newans = []
            for lev in level:
                newans.append(lev.val)
                if lev.left:
                    newlevel.append(lev.left)
                if lev.right:
                    newlevel.append(lev.right)
            if newans: ans.append(newans)
            level = newlevel
        for i in range(1, len(ans), 2):
            ans[i] = ans[i][::-1]
        return ans