标签:binarys queue list collections
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 as:
[ [15,7], [9,20], [3] ]
与Binary Tree Level Order Traversal完全一致 只要最后将Binary Tree Level Order Traversal的结果翻转一下 可以利用Collections的reverse函数 代码如下:
public class Solution { public List<List<Integer>> levelOrderBottom(TreeNode root) { List<Integer> tmp=new ArrayList<Integer>(); List<List<Integer>> res=new ArrayList<List<Integer>>(); if(root==null) return res; int count=1; int level=0; Queue<TreeNode> que =new LinkedList<TreeNode>(); que.offer(root); while(que.isEmpty()!=true){ tmp.clear(); level=0; for(int i=0;i<count;i++){ root=que.peek(); tmp.add(root.val); que.poll(); if(root.left!=null){ que.offer(root.left); level++; } if(root.right!=null){ que.offer(root.right); level++; } } List<Integer> tmpa=new ArrayList<Integer>(); tmpa.addAll(tmp); count=level; res.add(tmpa); } Collections.reverse(res); return res; } }
Binary Tree Level Order Traversal II
标签:binarys queue list collections
原文地址:http://blog.csdn.net/u012734829/article/details/42266053