首页 > 其他 > 详细

【树】

时间:2020-05-02 13:58:42      阅读:43      评论:0      收藏:0      [点我收藏+]

题目:

技术分享图片

 

 

解答:

 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 };

 

【树】

原文:https://www.cnblogs.com/ocpc/p/12817695.html

(0)
(0)
   
举报
评论 一句话评论(0
关于我们 - 联系我们 - 留言反馈 - 联系我们:wmxa8@hotmail.com
© 2014 bubuko.com 版权所有
打开技术之扣,分享程序人生!