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 20/15 7
Return its bottom-up level order traversal as:
[[15,7], [9,20], [3]]
Idea, the use of breadth-first search strategy, using the queue as a data structure, when a layer of nodes pressed into the queue, then take out the next layer of nodes of the layer node all pressed into the queue, then perform operations, layer and layer, using NULL node segmentation
Another problem is that we handle the data as top-down, but the output is bottom-up, so I define another list and pour the result list backwards into the target list
/**
* Definition for a binary tree node.
* Public class TreeNode {
* int val;
* TreeNode left;
* TreeNode right;
* TreeNode (int x) {val = x;}
* }
*/
public class Solution {
int count (TreeNode x)
{
if (x==null)
return 0;
Else
{
int Lc=count (x.left);
int Rc=count (x.right);
return lc+rc+1;
}
}
int height (TreeNode x)
{
if (x==null)
return 0;
Else
{
int Lh=height (x.left);
int Rh=height (x.right);
if (LH>RH)
return lh+1;
Else
return rh+1;
}
}
Treenode[] queue;
int start=0;
int end=0;
int size=0;
void Enqueue (TreeNode x)
{
Queue[start]=x;
if (IsEmpty ())
End= (end+1)%size;
Start= (start+1)%size;
}
TreeNode Outqueue ()
{
Start= (start-1)%size;
End= (end+1)%size;
Return queue[(end-1)%size];
}
Boolean IsEmpty ()
{
if (End==start)
return true;
Else
return false;
}
Public list<list<integer>> Levelorderbottom (TreeNode root) {
List<list<integer>> listl=new arraylist<list<integer>> ();
List<list<integer>> listend=new arraylist<list<integer>> ();
Size= (count (Root) +1) *10;
int h=height (root);
List<integer>[] v;
for (int i=0;i
V[i]=new arraylist<integer> ();
Queue=new Treenode[size];
for (int i=0;i<size;i++)
Queue[i]=new TreeNode (0);
TreeNode Y=null;
Enqueue (root);
Enqueue (y);
int c=0;
while (!isempty ())
{
Boolean t=false;
List<integer> l=new arraylist<integer> ();
TreeNode Z=outqueue ();
while (Z!=null)
{
L.add (Z.val);
if (z.left!=null)
{
Enqueue (Z.left);
T=true;
}
if (z.right!=null)
{
Enqueue (Z.right);
T=true;
}
Z=outqueue ();
}
if (!l.isempty ())
Listl.add (l);
if (t)
{
Enqueue (y);
C + +;
}
}
Here is the reverse output, which turns the output from top to bottom
for (int j=listl.size () -1;j>=0;j--)
Listend.add (Listl.get (j));
return listend;
}
}
Leetcode#107binary Tree level Order traversal II