原题地址
题目内容
题目分析
题目要求的是整棵树每一层最大的数。最开始想到的就是层序遍历,从上到下,从左到右遍历,把每一层最大的数存起来。后面参考了leetcode上面的discuss。发现还有另外一种做法,就是采用先序遍历,并且用depth来记录当前访问到第几层,由于每层只会有一个最大值,所以如果depth+1>result.size(),那么说明访问到了新的一层(因为depth是从0开始计数的),将当前的节点值push进result,result的size就变大了。否则就需要比较当前节点值与result[depth]值的大小了。
要注意一点的就是每一次访问的时候要注意空节点
代码实现
先序遍历
/**
* 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> res;
void findvalue(TreeNode* root, int depth){
if(root == NULL){
return;
}
if(res.size() < depth+1){
res.push_back(root->val);
}else{
if(root->val > res[depth]){
res[depth] = root->val;
}
}
findvalue(root->left,depth+1);
findvalue(root->right,depth+1);
}
vector<int> largestValues(TreeNode* root) {
if(root == NULL){
return res;
}
findvalue(root,0);
return res;
}
};
层级遍历
/**
* 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;
queue<TreeNode*> p;
if(root == NULL){
return res;
}
p.push(root);
while(!p.empty()){
int size = p.size();
int max = INT_MIN;//int整型当中最小的数
for(int i = 0; i < size; i++){
TreeNode*q = p.front();
p.pop();
if(q->val > max){
max = q->val;
}
if(q->left){
p.push(q->left);
}
if(q->right){
p.push(q->right);
}
}
res.push_back(max);
}
return res;
}
};