Tree find-largest-value-in-each-tree-row

1562 단어
rt, 코드는 다음과 같습니다.
  //Definition for singly-linked list.
  struct ListNode {
      int val;
      ListNode *next;
      ListNode(int x) : val(x), next(NULL) {}
 };

void travelTree(TreeNode* root){
        queue 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 findValueMostElement(TreeNode* root) {
        if(root == nullptr) return {};
        queue q;
        queue level;
        
        q.push(root);
        level.push(0);
        vector 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;
    }
};

좋은 웹페이지 즐겨찾기