Leetcode 103. 二叉树的锯齿形层序遍历 (每日一题 20210924)
生活随笔
收集整理的這篇文章主要介紹了
Leetcode 103. 二叉树的锯齿形层序遍历 (每日一题 20210924)
小編覺得挺不錯的,現在分享給大家,幫大家做個參考.
給定一個二叉樹,返回其節點值的鋸齒形層序遍歷。(即先從左往右,再從右往左進行下一層遍歷,以此類推,層與層之間交替進行)。例如:
給定二叉樹?[3,9,20,null,null,15,7],3/ \9 20/ \15 7
返回鋸齒形層序遍歷如下:[[3],[20,9],[15,7]
]鏈接:https://leetcode-cn.com/problems/binary-tree-zigzag-level-order-traversalclass Solution:def zigzagLevelOrder(self, root: TreeNode) -> List[List[int]]:# if not root:return []# cur_level,res = [root], []# depth = 0# while cur_level:# next_level = []# tmp = []# for node in cur_level:# tmp.append(node.val)# if node.left:# next_level.append(node.left)# if node.right:# next_level.append(node.right)# if depth % 2 == 1:# res.append(tmp[::-1])# else:# res.append(tmp)# depth += 1# cur_level = next_level# return resres = []def helper(root, depth):if not root:return if len(res) == depth:res.append([])if depth % 2 == 0:res[depth].append(root.val)else:res[depth].insert(0, root.val)helper(root.left, depth + 1)helper(root.right, depth + 1)helper(root,0)return res
總結
以上是生活随笔為你收集整理的Leetcode 103. 二叉树的锯齿形层序遍历 (每日一题 20210924)的全部內容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: Leetcode 155. 最小栈 (每
- 下一篇: Leetcode 59. 螺旋矩阵 II