码迷,mamicode.com
首页 > 其他好文 > 详细

LeetCode Binary Tree Level Order Traversal II

时间:2014-10-20 23:17:30      阅读:261      评论:0      收藏:0      [点我收藏+]

标签: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

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!