【力扣 - 二叉树的直径】

题目描述

给你一棵二叉树的根节点,返回该树的 直径 。
二叉树的 直径 是指树中任意两个节点之间最长路径的 长度 。这条路径可能经过也可能不经过根节点 root 。
两节点之间路径的 长度 由它们之间边数表示。
在这里插入图片描述

提示:

树中节点数目在范围 [1, 10000]

-100 <= Node.val <= 100

题解

/**
 * Definition for a binary tree node.
 * struct TreeNode {
 *     int val;
 *     struct TreeNode *left;
 *     struct TreeNode *right;
 * };
 */
int maxLen(struct TreeNode* root)
{
   
    if(root == NULL)
    {
   
        return 0; // Base case: return 0 if the current node is NULL
    }
    int leftLen;
    int rightLen;
    
    // Calculate the maximum path length of the left subtree
    leftLen = maxLen(root->left) + 1;
    
    // Calculate the maximum path length of the right subtree
    rightLen = maxLen(root->right) + 1;
    
    // Return the maximum of the left and right path lengths
    return leftLen > rightLen ? leftLen : rightLen;
}

int Traversal(struct TreeNode* root)
{
   
    if(root == NULL)
    {
   
        return INT_MIN; // Return minimum integer value if the current node is NULL
    }
    
    int diameter = INT_MIN; // Initialize diameter to minimum integer value
    
    // Calculate the diameter passing through the current node
    diameter = maxLen(root->left) + maxLen(root->right);
    
    // Update diameter with the maximum of diameter, left subtree traversal, and right subtree traversal
    diameter = fmax(diameter, Traversal(root->left));
    diameter = fmax(diameter, Traversal(root->right));
    
    return diameter; // Return the final diameter value
}

int diameterOfBinaryTree(struct TreeNode* root)
{
   
    // Post-order traversal to calculate the diameter of the binary tree
    return Traversal(root);
}

相关推荐

最近更新

  1. TCP协议是安全的吗?

    2024-02-22 15:38:05       18 阅读
  2. 阿里云服务器执行yum,一直下载docker-ce-stable失败

    2024-02-22 15:38:05       19 阅读
  3. 【Python教程】压缩PDF文件大小

    2024-02-22 15:38:05       18 阅读
  4. 通过文章id递归查询所有评论(xml)

    2024-02-22 15:38:05       20 阅读

热门阅读

  1. 力扣96不同的二叉搜索树详解

    2024-02-22 15:38:05       26 阅读
  2. hsv Matlab

    2024-02-22 15:38:05       31 阅读
  3. 向量数据库Milvus字符串查询

    2024-02-22 15:38:05       27 阅读
  4. JVM调优

    JVM调优

    2024-02-22 15:38:05      22 阅读
  5. el-select加上搜索查询时,限制开头空格输入

    2024-02-22 15:38:05       32 阅读
  6. 微众银行:始于数字原生,立于普惠金融

    2024-02-22 15:38:05       27 阅读
  7. 主流无人机开源飞控

    2024-02-22 15:38:05       33 阅读
  8. 大模型中的token是什么?

    2024-02-22 15:38:05       30 阅读