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