【树】

题目:

解答:

 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>> levelOrderBottom(TreeNode* root) 
13     {
14         vector< vector<int> > result;
15         if (root == NULL)
16             return result;
17 
18         queue<TreeNode*> q;
19         q.push(root);
20 
21         int count = 1;
22         int level = 0;
23 
24         vector<int> tmp(0);
25         while(!q.empty())
26         {
27             tmp.clear();
28             level = 0;
29 
30             for (int i = 0; i < count; ++i)
31             {
32                 root = q.front();
33                 q.pop();
34                 tmp.push_back(root->val);
35 
36                 if (root->left != NULL)
37                 {
38                     q.push(root->left);
39                     ++level;
40                 }
41                 if (root->right != NULL)
42                 {
43                     q.push(root->right);
44                     ++level;
45                 }
46             }
47 
48             count = level;
49             result.push_back(tmp);
50         }
51         reverse(result.begin(), result.end());
52         return result;
53         
54     }
55 };

猜你喜欢

转载自www.cnblogs.com/ocpc/p/12817695.html