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;
    }
};

猜你喜欢

转载自blog.csdn.net/qq_41814429/article/details/84947044