标签:des style blog color io ar for sp div
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] ]
1 /** 2 * Definition for binary tree 3 * public class TreeNode { 4 * int val; 5 * TreeNode left; 6 * TreeNode right; 7 * TreeNode(int x) { val = x; } 8 * } 9 */ 10 public class Solution { 11 public List<List<Integer>> levelOrderBottom(TreeNode root) { 12 LinkedList<List<Integer>> resList= new LinkedList<>(); 13 14 if (root==null) { 15 return resList; 16 } 17 18 Deque<TreeNode> visitDeque=new LinkedList<>(); 19 List<Integer> currList; 20 visitDeque.add(root); 21 int count=1; 22 int level=0; 23 while (!visitDeque.isEmpty()) { 24 level=0; 25 currList=new ArrayList<Integer>(); 26 for (int i = 0; i < count; i++) { 27 TreeNode node=visitDeque.pop(); 28 currList.add(node.val); 29 if (node.left != null) { 30 ++level; 31 visitDeque.add(node.left); 32 } 33 if (node.right != null) { 34 ++level; 35 visitDeque.add(node.right); 36 } 37 } 38 count=level; 39 resList.addFirst(currList); 40 } 41 return resList; 42 } 43 }
LeetCode Binary Tree Level Order Traversal II
标签:des style blog color io ar for sp div
原文地址:http://www.cnblogs.com/birdhack/p/4039048.html