【树】515. 在每个树行中找最大值

题目:

解法:

层次遍历就好,然后找出每层的最大的值,进行保存。

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

猜你喜欢

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