Find Largest Value in Each Tree Row
You need to find the largest value in each row of a binary tree.

解析
找到每一层的最大节点值。
解法1:层序遍历
直接层次遍历每一层,获得最大值。
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 size = q.size();
int m = INT_MIN;
for(int i=0;i<size;i++){
TreeNode* p = q.front();
q.pop();
m = max(m, p->val);
if(p->left) q.push(p->left);
if(p->right) q.push(p->right);
}
res.push_back(m);
}
return res;
}
};
解法2:递归,DFS
深度搜索树,当res大小等于深度时,增加res节点,当小于时,直接比较取最大值。
class Solution {
public:
vector<int> largestValues(TreeNode* root) {
vector<int> res;
DFS(root, 0, res);
return res;
}
void DFS(TreeNode* root, int level, vector<int>& res){
if(!root) return;
if(res.size() == level)
res.push_back(root->val);
else
res[level] = max(res[level], root->val);
DFS(root->left, level+1, res);
DFS(root->right, level+1, res);
}
};
本文介绍了一种算法,用于找出二叉树每一层的最大值。提供了两种解法:一是通过层序遍历直接获取每一层的最大值;二是采用递归深度优先搜索的方式更新最大值。
418

被折叠的 条评论
为什么被折叠?



