Binary Tree Level Order Traversal

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]
]

 

confused what "{1,#,2,3}" means? > read more on how binary tree is serialized on OJ.

 

Analyse: 

1. Recursion: If the level does not exist, create it and then push corresponding value into it. 

Runtime: 4ms.

 1 /**
 2  * Definition for a binary tree node.
 3  * struct TreeNode {
 4  *     int val;
 5  *     TreeNode *left;
 6  *     TreeNode *right;
 7  *     TreeNode(int x) : val(x), left(NULL), right(NULL) {}
 8  * };
 9  */
10 class Solution {
11 public:
12     vector<vector<int>> levelOrder(TreeNode* root) {
13         vector<vector<int> >result;
14         traverse(root, 0, result);
15         return result;
16     }
17     void traverse(TreeNode* root, int level, vector<vector<int> >& result){
18         if(!root) return;
19         if(level == result.size()) //the level does not exist and need to create it
20             result.push_back(vector<int> ());
21         
22         result[level].push_back(root->val);
23         traverse(root->left, level + 1, result);
24         traverse(root->right, level + 1, result);
25     }
26 };

 

2. Iteration: Using queue to store nodes. When poping the first node, we need to add its children(child) to the queue. Then keep poping until the queue is empty.

    Runtime: 8ms.

 1 /**
 2  * Definition for a binary tree node.
 3  * struct TreeNode {
 4  *     int val;
 5  *     TreeNode *left;
 6  *     TreeNode *right;
 7  *     TreeNode(int x) : val(x), left(NULL), right(NULL) {}
 8  * };
 9  */
10 class Solution {
11 public:
12     vector<vector<int> > levelOrder(TreeNode* root) {
13         vector<vector<int> > result;
14         if(!root) return result;
15         
16         queue<TreeNode* > qu;
17         qu.push(root);
18         while(!qu.empty()){
19             int n = qu.size();
20             vector<int> level; //store the visited nodes in current level
21             while(n--){
22                 TreeNode* temp = qu.front(); //pop the first node in the queue
23                 level.push_back(temp->val);
24                 qu.pop();
25                 if(temp->left) qu.push(temp->left); //add its children(child)
26                 if(temp->right) qu.push(temp->right);
27             }
28             result.push_back(level);
29         }
30         return result;
31     }
32 };

 

posted @ 2015-07-27 22:00  amazingzoe  阅读(210)  评论(0编辑  收藏  举报