LeetCode102 Binary Tree level Order traversal Java

Source: Internet
Author: User

Exercises

Given a binary tree, return the level order traversal of its nodes ' values. (ie, from left-to-right, level by level).

For example:
Given binary Tree {3,9,20,#,#,15,7} ,

    3   /   9    /   7

Return its level order traversal as:

[  3],  [9,20],  [15,7]]

Answer:

Sequence traversal, a layer of nodes exist in a queue, and then sequentially traverse each node of the queue, if its child nodes are not empty continue to join the queue when the queue is empty traversal end

Code:

public static list<list<integer>> Levelorder (TreeNode root) {      list<list<integer>> result =new arraylist<list<integer>> ();//Returns the final result   queue<treenode> treenodes2=new LinkedList<> ();//the node used to store each layer      //Handle the first node (root)   if (root==null)   return result;   else {   list<integer> temp=new arraylist<> ();//Store temporary results   temp.add (root.val);   Treenodes2.offer (root);   Result.add (temp);     }    while (!treenodes2.isempty ())   {  int i=treenodes2.size ();  List<integer> tempreslut=new arraylist<> ()///store temporary results while  (i>0)//traverse all nodes of this layer  {    TreeNode Tnode=treenodes2.poll ();  if (tnode.left!=null)  {  tempreslut.add (tNode.left.val);  Treenodes2.offer (Tnode.left);  }  if (tnode.right!=null)  {  tempreslut.add (tNode.right.val);  Treenodes2.offer (tnode.right);  }  i--;  }  if (!tempreslut.isempty ()) Result.add (Tempreslut);     }      return result;    }


Copyright NOTICE: This article for Bo Master original article, without Bo Master permission not reproduced.

LeetCode102 Binary Tree level Order traversal Java

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.