题目来源:
https://leetcode.com/problems/binary-tree-zigzag-level-order-traversal/
题意分析:
Z字宽度遍历树。
题目思路:
这题可以用比较取巧的方法。首先获得宽度遍历的结果,然后将第二层的翻转就可以了。
代码(python):
# Definition for a binary tree node. # class TreeNode(object): # def __init__(self, x): # self.val = x # self.left = None # self.right = None class Solution(object): def zigzagLevelOrder(self, root): """ :type root: TreeNode :rtype: List[List[int]] """ ans = [] def bfs(root,level): if root != None: if len(ans) < level + 1: ans.append([]) ans[level].append(root.val) bfs(root.left,level + 1) bfs(root.right,level + 1) bfs(root,0) i = 1 while i < len(ans): ans[i].reverse() i += 2 return ans
时间: 2024-10-05 23:50:20