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

Solution: Queue version. On the basis of 'Binary Tree Level Order Traversal', reverse the final vector.

     NULL is used to make gap between levels.

 1 /**
 2  * Definition for binary tree
 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> > levelOrderBottom(TreeNode *root) {
13         vector<vector<int> > res;
14         queue<TreeNode*> q;
15         if(!root) return res;
16         q.push(root);
17         q.push(NULL);
18         vector<int> level;
19         
20         while(true) {
21             TreeNode* node = q.front();
22             q.pop();
23             if(node) {
24                 level.push_back(node->val);
25                 if(node->left) q.push(node->left);
26                 if(node->right) q.push(node->right);
27             }
28             else {
29                 res.push_back(level);
30                 level.clear();
31                 if(q.empty()) break;
32                 q.push(NULL);
33             }
34         }
35         
36         reverse(res.begin(), res.end());
37         return res;
38     }
39 };

 

 

posted @ 2014-04-07 11:33  beehard  阅读(125)  评论(0编辑  收藏  举报