Question:
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)遍历整棵树,同时增加一个count来判断该数是不是处于同一层次的数字,再来判断大小关系。
代码实现如下:
/**
* 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> res;
public:
void Tree(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;
}
Tree(root->left,count+1);
Tree(root->right,count+1);
//return res;
}
vector<int> largestValues(TreeNode* root) {
if(root == NULL)return res;
Tree(root,0);
return res;
}
};