问题描述:
You need to find the largest value in each row of a binary tree.
Example:
Input: 1 / \ 3 2 / \ \ 5 3 9 Output: [1, 3, 9]
解题思路:
由于是计算每层的最大值,故可以在遍历该层次的时候去比较大小。
class Solution {
public:
vector<int> largestValues(TreeNode* root) {
vector<int> sum;
if(root==NULL) return sum;
sum.push_back(root->val);
dfs(root->left,1,sum);
dfs(root->right,1,sum);
return sum;
}
void dfs(TreeNode* root,int level,vector<int> &nums)
{
if(root==NULL) return;
else if(nums.size()<level+1)
nums.push_back(root->val);
else nums[level]=max(nums[level],root->val);
dfs(root->left,level+1,nums);
dfs(root->right,level+1,nums);
}
};