[leetcode]515. Find Largest Value in Each Tree Row
Analysis
啊啊啊啊啊啊—— [生死有命富贵在天]
You need to find the largest value in each row of a binary tree.
层序遍历,然后找到每一层的最大值就行了~
Implement
方法一(层序遍历)
/**
* Definition for a binary tree node.
* struct TreeNode {
* int val;
* TreeNode *left;
* TreeNode *right;
* TreeNode(int x) : val(x), left(NULL), right(NULL) {}
* };
*/
class Solution {
public:
vector<int> largestValues(TreeNode* root) {
vector<int> res;
if(!root)
return res;
queue<TreeNode*> q;
q.push(root);
while(!q.empty()){
int len = q.size();
int max_val = INT_MIN;
for(int i=0; i<len; i++){
TreeNode* cur = q.front();
q.pop();
max_val = max(max_val, cur->val);
if(cur->left)
q.push(cur->left);
if(cur->right)
q.push(cur->right);
}
res.push_back(max_val);
}
return res;
}
};
方法二(DFS,好像会快一点,但是我也不知道为啥。。。)
/**
* Definition for a binary tree node.
* struct TreeNode {
* int val;
* TreeNode *left;
* TreeNode *right;
* TreeNode(int x) : val(x), left(NULL), right(NULL) {}
* };
*/
class Solution {
public:
vector<int> largestValues(TreeNode* root) {
vector<int> maxs;
find(root, 0, maxs);
return maxs;
}
private:
void find(TreeNode* node, int row, vector<int>& maxs) {
if (!node) {
return;
}
if (row >= maxs.size()) {
maxs.push_back(node->val);
}
else {
maxs[row] = max(maxs[row], node->val);
}
find(node->left, row + 1, maxs);
find(node->right, row + 1, maxs);
}
};