首页 > 代码库 > Binary Tree Level Order Traversal leetcode java

Binary Tree Level Order Traversal leetcode java

题目

Given a binary tree, return the level order traversal of its nodes‘ values. (ie, from left to right, level by level).

For example:
Given binary tree {3,9,20,#,#,15,7},

    3   /   9  20    /     15   7

return its level order traversal as:

[  [3],  [9,20],  [15,7]]

题解
这道题就是用传统的BFS来做。代码如下:
 1    public ArrayList<ArrayList<Integer>> levelOrder(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         int curLevCnt = 1;  
 9         int nextLevCnt = 0;  
10         ArrayList<Integer> levelres = new ArrayList<Integer>();  
11         
12         while(!queue.isEmpty()){  
13             TreeNode cur = queue.poll();  
14             curLevCnt--;  
15             levelres.add(cur.val);  
16             
17             if(cur.left != null){  
18                 queue.add(cur.left);  
19                 nextLevCnt++;  
20             }  
21             if(cur.right != null){  
22                 queue.add(cur.right);  
23                 nextLevCnt++;  
24             }  
25               
26             if(curLevCnt == 0){  
27                 curLevCnt = nextLevCnt;  
28                 nextLevCnt = 0;  
29                 res.add(levelres);  
30                 levelres = new ArrayList<Integer>();  
31             }  
32         }  
33         return res;  
34     }