• [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
  • 相关阅读:
    子类继承方法的重写
    操作系统的用户模式和内核模式
    Java中的CAS
    FaceBook SDK登录功能实现(Eclipse)
    eclipse集成ijkplayer项目
    android handler传递数据
    android发送短信
    hadoop中的job.setOutputKeyClass与job.setMapOutputKeyClass
    mysql对事务的支持
    使用jd-gui+javassist修改已编译好的class文件
  • 原文地址:https://www.cnblogs.com/immjc/p/8320999.html
Copyright © 2020-2023  润新知