#Leetcode# 515. Find Largest Value in Each Tree Row
https://leetcode.com/problems/find-largest-value-in-each-tree-row/
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]
代码:
/**
* 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> ans;
if(!root) return ans;
helper(root, ans, 1);
return ans;
}
void helper(TreeNode* root, vector<int>& ans, int depth) {
if(depth > ans.size()) ans.push_back(root -> val);
else ans[depth - 1] = max(ans[depth - 1], root -> val);
if(root -> left) helper(root -> left, ans, depth + 1);
if(root -> right) helper(root -> right, ans, depth + 1);
}
};
今天是不吃宵夜的第二天!!!今天也是被二叉树折磨得死去活来的一天

浙公网安备 33010602011771号