zoukankan      html  css  js  c++  java
  • [LeetCode] Find Largest Value in Each Tree Row

     

    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]

    找出二叉树中每一层最大的元素。

    思路:利用层次遍历找出每一层最大元素即可。

    /**
     * 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> res;
            if (root == nullptr)
                return res;
            queue<TreeNode*> q;
            q.push(root);
            while (!q.empty()) {
                int n = q.size();
                int maxVal = INT_MIN;
                for (int i = 0; i < n; i++) {
                    TreeNode* node = q.front();
                    q.pop();
                    maxVal = max(maxVal, node->val);
                    if (node->left != nullptr)
                        q.push(node->left);
                    if (node->right != nullptr)
                        q.push(node->right);
                }
                res.push_back(maxVal);
            }
            return res;
        }
    };
    // 14 ms

     思路:使用递归dfs来查找每层最大值。

    /**
     * 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> res;
            dfs(root, 0, res);
            return res;
        }
        
        void dfs(TreeNode* node, int height, vector<int>& res) {
            if (node == nullptr)
                return;
            if (height >= res.size()) {
                res.push_back(node->val);
            }
            else {
                res[height] = max(res[height], node->val);
            }
            dfs(node->left, height + 1, res);
            dfs(node->right, height + 1, res);
        }
    };
    // 13 ms
  • 相关阅读:
    css 选择器
    IIS6、7添加反向代理的步骤
    使用脚本监控windows服务的方法
    ueditor编辑器插件 chrome中图片上传框延时问题
    Mysql隐式类型转换原则
    ASP.NET MVC 分页问题
    .NET程序集引用COM组件MSScriptControl所遇到的问题
    Makefile学习笔记
    操作系统的主要功能
    Linux基本命令之用户系统相关命令
  • 原文地址:https://www.cnblogs.com/immjc/p/8320999.html
Copyright © 2011-2022 走看看