• 515. Find Largest Value in Each Tree Row


    问题:

    给定二叉树,求每层最大节点,返回。

    Example 1:
    Input: root = [1,3,2,5,3,null,9]
    Output: [1,3,9]
    
    Example 2:
    Input: root = [1,2,3]
    Output: [1,3]
    
    Example 3:
    Input: root = [1]
    Output: [1]
    
    Example 4:
    Input: root = [1,null,2]
    Output: [1,2]
    
    Example 5:
    Input: root = []
    Output: []
     
    Constraints:
    The number of nodes in the tree will be in the range [0, 104].
    -231 <= Node.val <= 231 - 1

    example 1:

    解法:BFS

    queue存储每层node,处理每层节点时,对每个节点求max。

    代码参考:

     1 /**
     2  * Definition for a binary tree node.
     3  * struct TreeNode {
     4  *     int val;
     5  *     TreeNode *left;
     6  *     TreeNode *right;
     7  *     TreeNode() : val(0), left(nullptr), right(nullptr) {}
     8  *     TreeNode(int x) : val(x), left(nullptr), right(nullptr) {}
     9  *     TreeNode(int x, TreeNode *left, TreeNode *right) : val(x), left(left), right(right) {}
    10  * };
    11  */
    12 class Solution {
    13 public:
    14     vector<int> largestValues(TreeNode* root) {
    15         vector<int> res;
    16         queue<TreeNode*> q;
    17         if(root) q.push(root);
    18         int tmpmax;
    19         while(!q.empty()) {
    20             int sz = q.size();
    21             tmpmax = q.front()->val;
    22             for(int i=0; i<sz; i++) {
    23                 TreeNode* cur = q.front();
    24                 q.pop();
    25                 tmpmax = max(tmpmax, cur->val);
    26                 if(cur->left) q.push(cur->left);
    27                 if(cur->right) q.push(cur->right);
    28             }
    29             res.push_back(tmpmax);
    30         }
    31         return res;
    32     }
    33 };
  • 相关阅读:
    python dataformat.py通用数据格式转化脚本
    python ftp操作脚本&常用函数
    函数的作用域
    阶段规划
    Linux 远程登录Windows图形界面
    php常用的几个算法
    书目列表【当前&后续】
    提高工作效率的工具[分享]
    浏览器的调试软件
    Linux回收站[改写rm防止误删文件无法恢复]
  • 原文地址:https://www.cnblogs.com/habibah-chang/p/14473780.html
Copyright © 2020-2023  润新知