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]
这道题我的办法是用DFS然后记录每个高度的值存在vector中,然后再分别排序
/**
* Definition for a binary tree node.
* struct TreeNode {
* int val;
* TreeNode *left;
* TreeNode *right;
* TreeNode(int x) : val(x), left(NULL), right(NULL) {}
* };
*/
int cur_depth;
vector<int>dep_que[1000];
void dfs(TreeNode*root,int depth){
if(root == NULL) return;
else {
if(cur_depth <= depth) cur_depth = depth;
dep_que[depth].push_back(root->val);
}
dfs(root->left, depth+1);
dfs(root->right, depth+1);
}
class Solution {
public:
vector<int> largestValues(TreeNode* root) {
vector<int>largest;
if(root == NULL) return largest;
for(int i = 0; i <= 1000; i++){
dep_que[i].clear();
}
cur_depth = 0;
dfs(root,0);
for(int i = 0; i <= cur_depth; i++){
sort(dep_que[i].begin(),dep_que[i].end());
int max_index = dep_que[i].size()-1;
largest.push_back(dep_que[i][max_index]);
}
return largest;
}
};