Source of the topic:
https://leetcode.com/problems/binary-tree-level-order-traversal/
Test Instructions Analysis:
Width first searches for a binary tree, where the same layer is placed in the same list. Like what:
3 / 9 / 7
Return
[ 3], [9,20], [15,7]]
Topic Ideas:
A new definition of a function, plus a number of layer parameters, if the current answer to the list of answers is equal to the number of layers, then the current number of layers of the list append new elements, the number of new layers.
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):defLevelorder (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)returnans
View Code
[Leetcode] (python): 102-binary Tree level Order traversal