Topic
Given a binary tree, return the bottom-up level order traversal of its nodes ' values. (ie, from the left-to-right, the level by level from the leaf to root).
For example:
Given binary Tree {3,9,20,#,#,15,7}
,
3 / 9 / 7
Return its bottom-up level order traversal as:
[ [15,7], [9,20], [3]]
Answer
Similar to binary Tree level Order traversal, just flips its results, the code is as follows:
/** * Definition for Binary tree * public class TreeNode {* int val, * TreeNode left, * TreeNode right; TreeNode (int x) {val = x;} *} */public class Solution {public list<list<integer>> Levelorderbottom (Tre Enode root) {list<list<integer>> ret=new arraylist<list<integer>> (); DFS (Root,0,ret); List<list<integer>> result=new arraylist<list<integer>> (); Flips the list for (int i=ret.size () -1;i>=0;i--) {Result.add (Ret.get (i)); } return result; }//Layered traversal-recursive private static void Dfs (TreeNode root,int level,list<list<integer>> ret) {if (root==nu ll) {return; }//Add a new Arrayl to represent the new layer if (Level>=ret.size ()) {Ret.add (New arraylist<integer> ());} Ret.get (Level). Add (Root.val); Add the node to the ArrayList that represents that layer Dfs (Root.left,level+1,ret); Recursive processing of the next layer of Saozi right subtree Dfs (Root.right,level+1,ret); }}//Iteration Method: Public list&Lt List<integer>> levelorderbottom (TreeNode root) {list<list<integer>> result=new ArrayList< List<integer>> (); if (root==null) {return result;} Queue<treenode> queue=new linkedlist<treenode> (); Queue.add (root); List<list<integer>> list=new arraylist<list<integer>> (); List<integer> item=new arraylist<integer> (); int Currentlevel=1;int nextlevel=0;while (!queue.isEmpty ()) {TreeNode cur=queue.remove (); Currentlevel--;item.add (cur.val); if (cur.left!=null) {queue.add (cur.left); nextLevel+ +;} if (cur.right!=null) {queue.add (cur.right); nextlevel++;} if (currentlevel==0) {List.add (item); item=new arraylist<integer> (); currentlevel=nextlevel;nextlevel=0;}} Flip listfor (int i=list.size () -1;i>=0;i--) {Result.add (List.get (i));} return result;}
---EOF---
"Leetcode" Binary Tree level Order traversal II