寻找二叉树每层的最大值,递归先序遍历的方法实现,利用一个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 {
vector<int> vecRecordMax;
public:
void findMAX(TreeNode* now, int level) {
if(now == NULL)
return;
if(vecRecordMax.size() <= level) { //no record
vecRecordMax.push_back(now->val);
} else {
if(now->val > vecRecordMax[level])
vecRecordMax[level] = now->val;
}
findMAX(now->left, level + 1);
findMAX(now->right, level + 1);
}
vector<int> largestValues(TreeNode* root) {
findMAX(root, 0);
return vecRecordMax;
}
};