Level Order Traversal of the tree and ArrayList flip
Package Level3; import java. util. arrayList; import java. util. using list; import java. util. queue; import Utility. treeNode;/*** Binary Tree Level Order Traversal II *** 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 {, 20, #, #,}, 3/\ 9 20/\ 15 7 return its botto M-up level order traversal as: [[15, 7] [9, 20], [3],] confused what "{1, #, 2, 3}" means?> Read more on how binary tree is serialized on OJ. OJ's Binary Tree Serialization: The serialization of a binary tree follows a level order traversal, where '# 'signiies a path terminator where no node exists below. here's an example: 1/\ 2 3/4 \ 5 The above binary tree is serialized as "{, 3, #,#, 4, #,#, 5 }". **/public class S107 {public static void main (String [] args) {} public ArrayLis T <ArrayList <Integer> levelOrderBottom (TreeNode root) {ArrayList <Integer> ret = new ArrayList <Integer> (); if (root = null) {return ret;} Queue <TreeNode> queue = new queue list <TreeNode> (); Queue. add (root); ArrayList <Integer> alal = new ArrayList <Integer> (); ArrayList <Integer> al = new ArrayList <Integer> (); // record the number of nodes at the current level and next level int currentLeve L = 1; int nextLevel = 0; while (! Queue. isEmpty () {TreeNode cur = queue. remove (); currentLevel --; al. add (cur. val); if (cur. left! = Null) {queue. add (cur. left); nextLevel ++;} if (cur. right! = Null) {queue. add (cur. right); nextLevel ++;} if (currentLevel = 0) {alal. add (al); al = new ArrayList <Integer> (); currentLevel = nextLevel; nextLevel = 0 ;}// flip ArrayList for (int I = alal. size ()-1; I> = 0; I --) {ret. add (alal. get (I) ;}return ret ;}}