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

102 Binary Tree Level Order Traversal

时间:2016-03-01 06:19:46      阅读:120      评论:0      收藏:0      [点我收藏+]

标签:

 1 /**
 2  * Definition for a binary tree node.
 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>> levelOrder(TreeNode root) {
12         List<List<Integer>> returnVal = new ArrayList<List<Integer>>();
13         if (root == null)
14             return returnVal;
15         Queue<TreeNode> nodes = new ArrayDeque<TreeNode>();
16         nodes.offer(root);
17         
18         Queue<TreeNode> nextLevel = new ArrayDeque<TreeNode>();
19         
20         List<Integer> currentList = new ArrayList<Integer>();
21         while(!nodes.isEmpty())
22         {
23             TreeNode next = nodes.poll();
24             currentList.add(next.val);
25             if(next.left != null)
26                 nextLevel.offer(next.left);
27             if(next.right != null)
28                 nextLevel.offer(next.right);
29             
30             if(nodes.isEmpty())
31             {
32                 nodes = nextLevel;
33                 nextLevel = new ArrayDeque<TreeNode>();
34                 returnVal.add(currentList);
35                 currentList = new ArrayList<Integer>();
36             }
37         }
38         
39         
40         return returnVal;
41     }
42 }

 

102 Binary Tree Level Order Traversal

标签:

原文地址:http://www.cnblogs.com/neweracoding/p/5229533.html

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