[Leetcode] [JAVA] Binary Tree level Order traversal

Source: Internet
Author: User

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]]

For each layer of the node is saved with arraylist<treenode> cur, each time the loop cur each non-empty node value is taken out and saved to arraylist<integer> temp, And the child nodes are saved to the new arraylist<treenode>. Finally, if temp is not empty, it is added to the result set. Finally cur points to the new arraylist<treenode>.

1  PublicList<list<integer>>Levelorder (TreeNode root) {2list<list<integer>> re =NewArraylist<list<integer>>();3list<treenode> LST =NewArraylist<treenode>();4 Lst.add (root);5          while(Lst.size () >0){6list<integer> temp =NewArraylist<integer>();7List<treenode> Childrenlst =NewArraylist<treenode>();8              for(intI=0;i<lst.size (); i++){9TreeNode Curnode =Lst.get (i);Ten                 if(curnode!=NULL){ One Temp.add (Lst.get (i). val); A Childrenlst.add (curnode.left); - Childrenlst.add (curnode.right); -                 } the             } -             if(Temp.size () >0) - Re.add (temp); -LST =Childrenlst; +         } -         returnre; +}

Level Order Traverse II is counter-first.

[Leetcode] [JAVA] 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.