Question prototype:
Given a binary tree, return the bottom-up level order traversal of its nodes 'values. (ie, from left to right, level by level from leaf to root ).
For example:
Given binary tree{3,9,20,#,#,15,7}
,
3 / \ 9 20 / \ 15 7
Return its bottom-up level order traversal:
[ [15,7] [9,20], [3],]
Basic Ideas:
Stack is used because it is from the bottom up.
Public ArrayList> levelOrderBottom (TreeNode root) {Stack> stack = new Stack> (); ArrayList> list = new ArrayList> (); ArrayList
NodeSet = new ArrayList
(); ArrayList
Tmp; ArrayList
NumSet; if (root! = Null) {nodeSet. add (root); while (nodeSet. size ()> 0) {tmp = new ArrayList
(); NumSet = new ArrayList
(); // Add it to the stack for (TreeNode tn: nodeSet) numSet. add (tn. val); // Add to stack. push (numSet); // calculate the node next layer for (TreeNode it: nodeSet) {if (it. left! = Null) tmp. add (it. left); if (it. right! = Null) tmp. add (it. right);} nodeSet = tmp;} // add to list while (stack. size ()> 0) {ArrayList
Rs = stack. pop (); list. add (rs) ;}} return list ;}