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