515. Find Largest Value in Each Tree Row
程序员文章站
2022-05-18 20:26:45
...
515. 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]
方法1: dfs
思路:
/**
* 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, 0, res);
return res;
}
void dfs(TreeNode* root, int level, vector<int> & res) {
if (!root) return;
if (level == res.size()) res.push_back({INT_MIN});
res[level] = max(res[level], root -> val);
dfs(root -> left, level + 1, res);
dfs(root -> right, level + 1, res);
return;
}
};
上一篇: ELK:ElasticSearch 安装以及基本配置
下一篇: Recursion