Source of the topic:
https://leetcode.com/problems/binary-tree-zigzag-level-order-traversal/
Test Instructions Analysis:
The z-word width traverses the tree.
Topic Ideas:
This problem can be compared with the Trickery method. First get the result of the width traversal, and then flip the second layer to be able.
Code (Python):
#Definition for a binary tree node.#class TreeNode (object):#def __init__ (self, x):#self.val = x#self.left = None#self.right = Noneclasssolution (object):defZigzaglevelorder (self, root):""": Type Root:treenode:rtype:list[list[int]]"""ans= [] defBFS (root,level):ifRoot! =None:ifLen (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 whileI <len (ans): Ans[i].reverse () I+ = 2returnans
View Code
[Leetcode] (python): 103-binary Tree Zigzag level Order traversal