[Leetcode 80] 107 Binary Tree Level Order Traversal II

Problem:

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

 

Analysis:

This problem is an extension of the original level order traversal problem. The only extra thing need to do is to reverse the whole result vector before return.

One thing to remember is that, after exit the while loop in the program, the last level's result is not yet push into the result vector. This operation cannot be omitted.

 

Code:

 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         // Start typing your C/C++ solution below
14         // DO NOT write int main() function
15         vector<vector<int> > res;
16         if (root == NULL)
17             return res;
18             
19         queue<TreeNode *> q;
20         q.push(root);
21         
22         TreeNode *sentl = new TreeNode(-1);
23         sentl->left = NULL;
24         sentl->right = NULL;
25         q.push(sentl);
26         
27         TreeNode *tmp;
28         vector<int> pres;
29         while (q.size() !=1 ) {
30             tmp = q.front();
31             q.pop();
32             
33             if (tmp == sentl) {
34                 res.push_back(pres);
35                 pres.clear();
36                 q.push(sentl);
37             } else {
38                 pres.push_back(tmp->val);
39                 
40                 if (tmp->left != NULL)
41                     q.push(tmp->left);
42                 
43                 if (tmp->right != NULL)
44                     q.push(tmp->right);
45             }
46         }
47         res.push_back(pres);
48         
49         reverse(res.begin(), res.end());
50         
51         return res;
52     }
53 };
View Code

 

posted on 2013-07-23 02:36  freeneng  阅读(144)  评论(0编辑  收藏  举报

导航