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]
Subscribe to see which companies asked this question.
解题思路:
遍历还是通过dfs遍历,只是增加一个tag来判断该数是不是处于同一层次的(同一广度)的数字,再来判断大小关系。
#include <iostream>
#include <vector>
using namespace std;
class Solution {
vector<int> res;
public:
void Tra(TreeNode* root, int count) {
if(root == NULL)return;
if(res.size() < count +1) res.push_back(root->val);
else{
if(root->val > res[count])
res[count] = root->val;
}
Tra(root->left,count+1);
Tra(root->right,count+1);
//return res;
}
vector<int> largestValues(TreeNode* root) {
if(root == NULL)return res;
Tra(root,0);
return res;
}
};