[每日一题]36:在每个树行中找最大值

题目描述

您需要在二叉树的每一行中找到最大的值。

示例:

输入: 

      1
     / \
    3   2
   / \   \  
  5   3   9 

输出: [1, 3, 9]

解答代码:

/**
 * 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){
            return v;
        }

        queue<TreeNode*> qu;
        TreeNode* cur;
        int max;
        int len = 1;
        qu.push(root);

        while(!qu.empty()){
            max = qu.front()->val;
            for(int i = 0; i < len; i++){
                cur = qu.front();
                if(max < cur->val){
                    max = cur->val;
                }
                qu.pop();
                
                if(cur->left){
                    qu.push(cur->left);
                }
                if(cur->right){
                    qu.push(cur->right);
                }
            }
            v.push_back(max);
            len = qu.size();
        }

        return v;
    }
};

如有不同见解,欢迎留言讨论!

发布了152 篇原创文章 · 获赞 45 · 访问量 1万+

猜你喜欢

转载自blog.csdn.net/AngelDg/article/details/105420322