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

Leetcode: Binary Tree Level Order Transversal II

时间:2014-09-15 14:13:38      阅读:153      评论:0      收藏:0      [点我收藏+]

标签:des   style   blog   color   io   ar   for   div   sp   

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 Transversal的基础上难度:20,只需要对最后结果做一个倒序就好。格式是Collections.reverse(List<?> list)

 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 ArrayList<ArrayList<Integer>> levelOrderBottom(TreeNode root) {
12         ArrayList<ArrayList<Integer>> lists = new ArrayList<ArrayList<Integer>> ();
13         if (root == null) return lists;
14         LinkedList<TreeNode> queue = new LinkedList<TreeNode>();
15         queue.add(root);
16         int ParentNumInQ = 1;
17         int ChildNumInQ = 0;
18         ArrayList<Integer> list = new ArrayList<Integer>();
19         while (!queue.isEmpty()) {
20             TreeNode cur = queue.poll();
21             list.add(cur.val);
22             ParentNumInQ--;
23             if (cur.left != null) {
24                 queue.add(cur.left);
25                 ChildNumInQ++;
26             }
27             if (cur.right != null) {
28                 queue.add(cur.right);
29                 ChildNumInQ++;
30             }
31             if (ParentNumInQ == 0) {
32                 ParentNumInQ = ChildNumInQ;
33                 ChildNumInQ = 0;
34                 lists.add(list);
35                 list = new ArrayList<Integer>();
36             }
37         }
38         Collections.reverse(lists);
39         return lists;
40     }
41 }

 

Leetcode: Binary Tree Level Order Transversal II

标签:des   style   blog   color   io   ar   for   div   sp   

原文地址:http://www.cnblogs.com/EdwardLiu/p/3972648.html

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