• 【树】在每个树行中找最大值


    题目描述:https://leetcode-cn.com/problems/find-largest-value-in-each-tree-row/

    思路一:DFS

    •  定义数组maxNum[],其中下标为层数level,元素值为每层的最大值
    • 如果当前结点是遇到的某层的第一个结点则将该结点的键值存入数组,否则比较当前结点的键值和数组中已有的数值
    • 深度遍历树
     1 /**
     2  * Definition for a binary tree node.
     3  * struct TreeNode {
     4  *     int val;
     5  *     TreeNode *left;
     6  *     TreeNode *right;
     7  *     TreeNode(int x) : val(x), left(NULL), right(NULL) {}
     8  * };
     9  */
    10 class Solution {
    11 public:
    12     vector<int> largestValues(TreeNode* root) {
    13         largestValuesLevel(root,level);
    14         return maxNum;
    15     }
    16     //参数是当前结点和当前结点的层数
    17     void largestValuesLevel(TreeNode* node,int level){
    18         if(node==nullptr)
    19             return;
    20         //如果遍历到新的一层但是maxNum中还没有该层的值
    21         if(maxNum.size()<level+1)
    22             maxNum.push_back(node->val);
    23         else
    24             maxNum[level]=max(node->val,maxNum[level]);
    25         //深度遍历
    26         if(node->left)
    27             largestValuesLevel(node->left,level+1);
    28         if(node->right)
    29             largestValuesLevel(node->right,level+1);
    30     }
    31 private:
    32     vector<int>maxNum;
    33     int level=0;
    34 };

    思路二:BFS

     利用层序遍历的思想,将每一层的结点压入队列,然后循环比较队列中的各结点的键值找出最大的,同时每经历一个结点就将该结点的儿子入队

     1 /**
     2  * Definition for a binary tree node.
     3  * struct TreeNode {
     4  *     int val;
     5  *     TreeNode *left;
     6  *     TreeNode *right;
     7  *     TreeNode(int x) : val(x), left(NULL), right(NULL) {}
     8  * };
     9  */
    10 class Solution {
    11 public:
    12     vector<int> largestValues(TreeNode* root) {
    13         queue<TreeNode*>q;
    14         int idx=0;
    15         if(root==nullptr)
    16             return maxNum;
    17         q.push(root);
    18         while(!q.empty()){
    19             int cnt=q.size();//当前层的结点数
    20             int maxtmp=INT_MIN;
    21             for(int i=0;i<cnt;i++){
    22                 TreeNode* tmp=q.front();//定义当前结点
    23                 maxtmp=max(tmp->val,maxtmp);
    24                 if(tmp->left)
    25                     q.push(tmp->left);
    26                 if(tmp->right)
    27                     q.push(tmp->right);
    28                 q.pop();
    29             }
    30             maxNum.push_back(maxtmp);   
    31         }
    32         return maxNum;
    33     }
    34     
    35 private:
    36     vector<int>maxNum;
    37 };
  • 相关阅读:
    SpringMVC常用注解
    SpringMVC基础知识
    如何在git中恢复先前的提交?
    git pull 和git fetch的区别
    webpack和gulp的比较
    SpringMVC框架
    Spring框架
    为什么要在一个团队中开展软件测试工作?
    需求测试的注意事项有哪些?
    主键、外键的作用,索引的优点与不足?
  • 原文地址:https://www.cnblogs.com/PennyXia/p/12773368.html
Copyright © 2020-2023  润新知