Binary Tree Level Order Traversal II

Given a binary tree, return the bottom-up level order traversal of its nodes’ values. (ie, from left to right, level by level from leaf to root).

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

    3
   / \
  9  20
    /  \
   15   7

return its bottom-up level order traversal as:

[
  [15,7]
  [9,20],
  [3],
]
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> > levelOrderBottom(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         P.push(root);
21         vector<int> level;
22         while(P.size()!=0)
23         {
24             TreeNode* tmp=P.front();
25             P.pop();
26             level.push_back(tmp->val);
27             if(tmp->left!=NULL)
28             {
29                 Q.push(tmp->left);
30             }
31             if(tmp->right!=NULL)
32             {
33                 Q.push(tmp->right);
34             }
35             if(P.size()==0)
36             {
37                 result.push_back(level);
38                 level.clear();
39                 queue<TreeNode*> T=P;
40                 P=Q;
41                 Q=T;
42             }
43         }
44         int n=result.size();
45         int mid=n/2;
46         for(int i=0;i<mid;i++)
47         {
48             vector<int> tmp=result[i];
49             result[i]=result[n1i];
50             result[n1i]=tmp;
51         }
52         return result;
53     }
54 };
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