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
  • 相关阅读:
    华为oj之字符串分割
    华为oj之字符个数统计
    华为oj之等差数列前n项和
    华为oj之质数因子
    华为oj之求int型正整数在内存中存储时1的个数
    华为oj之字符串反转
    SpringBoot--表单验证
    SpringBoot--异常统一处理
    SpringBoot--文件上传
    SpringBoot--thymeleaf
  • 原文地址:https://www.cnblogs.com/immjc/p/8320999.html
Copyright © 2011-2022 走看看