[Description]:
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广度优先搜索,Solution中BFS(r, h)中的h负责记录节点所在的层次。vector<int> v每一个位置对应相应层次的最大值。
[Solution]:
/**
* 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) {
if (root != NULL) BFS(root, 0);
return v;
}
private:
std::vector<int> v;
void BFS(TreeNode* r, int h) {
if (v.size() > h && v[h] < r->val) {
v[h] = r->val;
} else if (v.size() == h) {
v.push_back(r->val);
}
if (r->left) {
BFS(r->left, h+1);
}
if (r->right) {
BFS(r->right, h+1);
}
}
};