标签:
题目:
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] ]
题解:
这道题跟前面一道是一样的。。
只是存到res的结果顺序不一样罢了。
之前那个就是循序的存
这道题就是每得到一个行结果就存在res的0位置,这样自然就倒序了。
代码如下:
1 public ArrayList<ArrayList<Integer>> levelOrderBottom(TreeNode root) { 2 ArrayList<ArrayList<Integer>> res = new ArrayList<ArrayList<Integer>>(); 3 if(root == null) 4 return res; 5 6 LinkedList<TreeNode> queue = new LinkedList<TreeNode>(); 7 queue.add(root); 8 9 int curLevCnt = 1; 10 int nextLevCnt = 0; 11 12 ArrayList<Integer> levelres = new ArrayList<Integer>(); 13 14 while(!queue.isEmpty()){ 15 TreeNode cur = queue.poll(); 16 curLevCnt--; 17 levelres.add(cur.val); 18 19 if(cur.left != null){ 20 queue.add(cur.left); 21 nextLevCnt++; 22 } 23 if(cur.right != null){ 24 queue.add(cur.right); 25 nextLevCnt++; 26 } 27 28 if(curLevCnt == 0){ 29 curLevCnt = nextLevCnt; 30 nextLevCnt = 0; 31 res.add(0,levelres); //insert one by one from the beginning 32 levelres = new ArrayList<Integer>(); 33 } 34 } 35 return res; 36 }
reference: http://www.cnblogs.com/springfor/p/3891392.html
*Binary Tree Level Order Traversal II
标签:
原文地址:http://www.cnblogs.com/hygeia/p/4704053.html