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
  • 相关阅读:
    491 · 回文数
    936 · 首字母大写
    1343 · 两字符串和
    1535 · 转换成小写字母
    13 · 字符串查找
    146 · 大小写转换 II
    241 · 转换字符串到整数(容易版)
    46 · 主元素
    kotlin协程——>通道
    kotlin协程——>异步流
  • 原文地址:https://www.cnblogs.com/immjc/p/8320999.html
Copyright © 2011-2022 走看看