rt,代码如下:
//Definition for singly-linked list.
struct ListNode {
int val;
ListNode *next;
ListNode(int x) : val(x), next(NULL) {}
};
void travelTree(TreeNode* root){
queue<TreeNode*> q;
q.push(root);
while(q.size()){
TreeNode *r = q.front(); q.pop();
if(r->left) {
q.push(r->left);
}
if(r->right){
q.push(r->right);
}
}
}
leetcode 上相关的题目:
https://leetcode.com/problems/find-largest-value-in-each-tree-row/#/solutions
class Solution {
public:
vector<int> findValueMostElement(TreeNode* root) {
if(root == nullptr) return {};
queue<TreeNode*> q;
queue<int> level;
q.push(root);
level.push(0);
vector<int> mac;
int m=-1;
while(q.size()){
TreeNode *r = q.front(); q.pop();
int l = level.front(); level.pop();
if(r->left) {
q.push(r->left);
level.push(l+1);
}
if(r->right){
q.push(r->right);
level.push(l+1);
}
if(l > m){
m = l;
mac.push_back(r->val);
} else {
mac[l] = std::max(mac[l], r->val);
}
}
return mac;
}
};