[Leetcode] (python): 102-binary Tree level Order traversal

Source: Internet
Author: User

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

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.