1. 程式人生 > >LC 515. Find Largest Value in Each Tree Row

LC 515. Find Largest Value in Each Tree Row

1.題目描述

515. Find Largest Value in Each Tree Row

Medium

41337

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]

2.解題思路

BFS遍歷每一層,比較每一層中最大的存入vector

3.程式碼

/**
 * 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> V;
        if (root==NULL) return V;
        queue<TreeNode*> Q;
        Q.push(root);
        while (!Q.empty()) {
            int n=Q.size();//下面用到,用於判斷是否是同一層
            int temp = -2147483648;
            for (int i=0; i<n; i++) {//處理一層的元素
                if (Q.front()->left) Q.push(Q.front()->left);
                if (Q.front()->right) Q.push(Q.front()->right);
                temp = max(temp, Q.front()->val);
                Q.pop();
            }
            V.push_back(temp);
        }
        return V;
    }
};