Binary Tree Level Order Traversal leetcode java

愛做飯的小瑩子發表於2014-08-05

題目

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     } 


相關文章