这道题的意思是,存下一棵二叉树每一行最大的数。
我的做法是,遍历这棵树,用一个变量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> largestValues(TreeNode* root) {
vector<int> res;
dfs(root, res, 1);
return res;
}
void dfs(TreeNode* root, vector<int>& res, int depth)
{
if(root == NULL)
return;
if(res.size() < depth)
{
res.push_back(root->val);
}
else
{
res[depth - 1] = max(res[depth - 1], root->val);
}
dfs(root->left, res, depth + 1);
dfs(root->right, res, depth + 1);
}
};