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]
方法一:用vector + 2个标识进行层序遍历,好处:可以方便地在同一层内进行遍历。
/**
* 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> solution;
vector<TreeNode*> nVector;
if (!root) return solution;
int cur = 0;
int end = 0;
nVector.push_back(root);
while(cur < nVector.size())
{
end = nVector.size();
int max = nVector[cur]->val;
while (cur < end) {
if (nVector[cur]->left) nVector.push_back(nVector[cur]->left);
if (nVector[cur]->right) nVector.push_back(nVector[cur]->right);
max = (max < nVector[cur]->val) ? nVector[cur]->val : max;
++cur;
}
solution.push_back(max);
}
return solution;
}
};
方法二:前序遍历(深度优先搜索)
class Solution {
public:
vector<int> largestValues(TreeNode* root) {
dfs(root, 0);
return solution;
}
void dfs (TreeNode* root, int level) {
if (!root) return;
if (solution.size() < level+1) solution.push_back(root->val);
else solution[level] = (root->val > solution[level]) ? root->val : solution[level];
dfs(root->left, level+1);
dfs(root->right, level+1);
}
private:
vector<int> solution;
};