- 描述: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]
分析:这道题要求找到每层树中最大的元素,并输出。
思路一:用bfs对整棵数进行搜索,并寻找最大值。我采用了set内置的排序对每层的元素进行排序,将每次得到的set的最后一个元素加入vector。
/**
* 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> result;
if (!root) return result;
set<int> my_set;
set<int>::iterator it;
queue<TreeNode*> my_queue;
result.push_back(root -> val);
my_queue.push(root);
while (!my_queue.empty()) {
int n = my_queue.size();
my_set.clear();
for (int i = 0; i < n; i ++) {
TreeNode* temp = my_queue.front();
my_queue.pop();
if (temp -> left) {
my_set.insert(temp -> left -> val);
my_queue.push(temp -> left);
}
if (temp -> right) {
my_set.insert(temp -> right -> val);
my_queue.push(temp -> right);
}
}
if (!my_set.empty()) {
it = my_set.end();
it--;
result.push_back(*it);
}
}
return result;
}
};
- 思路二:用递归的方式实现。(dfs)
class Solution {
public:
void dfs(TreeNode* root, vector<int>& result, int deepth) {
if (!root) return;
if (deepth > result.size()) result.push_back(root -> val);
else result[deepth - 1] = max(result[deepth - 1], root -> val);
dfs(root -> left, result, deepth + 1);
dfs(root -> right,result, deepth + 1);
}
vector<int> largestValues(TreeNode* root) {
vector<int> result;
if (!root) return result;
dfs(root, result, 1);
return result;
}
};