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]
]
C++:
01 /**
02  * Definition for binary tree
03  * struct TreeNode {
04  *     int val;
05  *     TreeNode *left;
06  *     TreeNode *right;
07  *     TreeNode(int x) : val(x), left(NULL), right(NULL) {}
08  * };
09  */
10 class Solution {
11 public:
12     vector<vector<int> > levelOrder(TreeNode *root) {
13         // Start typing your C/C++ solution below
14         // DO NOT write int main() function
15         vector<vector<int>> result;
16         if(root==NULL)
17             return result;
18         queue<TreeNode*> P;
19         queue<TreeNode*> Q;
20         vector<int> level;
21         P.push(root);
22         while(!P.empty())
23         {
24             TreeNode* tmp=P.front();
25             P.pop();
26             if(tmp->left!=NULL)
27             {
28                 Q.push(tmp->left);
29             }
30             if(tmp->right!=NULL)
31             {
32                 Q.push(tmp->right);
33             }
34             level.push_back(tmp->val);
35             if(P.empty())
36             {
37                 result.push_back(level);
38                 level.clear();
39                 queue<TreeNode*> T=P;
40                 P=Q;
41                 Q=T;
42             }
43         }
44         return result;
45     }
46 };
Advertisements
This entry was posted in Stack and Queue, Tree. Bookmark the permalink.

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s