zl程序教程

您现在的位置是:首页 >  后端

当前栏目

515. 在每个树行中找最大值-深度优先遍历

遍历 深度 每个 最大值 优先
2023-09-14 09:06:52 时间

515. 在每个树行中找最大值

给定一棵二叉树的根节点 root ,请找出该二叉树中每一层的最大值。

示例1:
在这里插入图片描述

输入: root = [1,3,2,5,3,null,9]
输出: [1,3,9]

示例2:

输入: root = [1,2,3]

对于这题个人做了一些优化,可以节省一些空间复杂度。解题代码如下:

/**
 * Definition for a binary tree node.
 * struct TreeNode {
 *     int val;
 *     struct TreeNode *left;
 *     struct TreeNode *right;
 * };
 */


/**
 * Note: The returned array must be malloced, assume caller calls free().
 */
 int  high_tree(struct TreeNode* root){
     if(root){
         int a=high_tree(root->left)+1;
         int b=high_tree(root->right)+1;
         return fmax(a,b);
     }
     else{
         return 0;
     }
 }
void find_max(struct TreeNode* root,int now_h,int *re){
     if(root){
         if(root->val>re[now_h]){
             re[now_h]=root->val;
         }
         find_max(root->left,now_h+1,re);
         find_max(root->right,now_h+1,re);
         
     }
  
 }


int* largestValues(struct TreeNode* root, int* returnSize){
    int h=high_tree(root);
    int *re=(int *)malloc(sizeof(int)*h);
    for(int i=0;i<h;i++){
        re[i]=-2147483648;
    }   
     find_max(root,0,re);
    * returnSize=h;
    return re;

}