leetcode543--二叉树的直径

文章讨论了如何在给定的二叉树中找到最远两个节点之间的距离,提供了暴力解法和动态规划两种方法。暴力解法通过递归计算左右子树的深度,动态规划则在求深度的过程中更新答案。
摘要由CSDN通过智能技术生成

1. 题意

求二叉树上最远两个节点之间的距离。

2. 题解

2.1 暴力

最长路径的三种情况

  • 通过根节点
  • 在左子树
  • 在右子树
            1
         2    
     4     5  
  6  7   8   9 
  diameter =  5

通过根节点的最长路径长度一定是左右子树深度之和。

但是这样求左右子树的深度会不断重复,所以复杂度很高。

/**
 * Definition for a binary tree node.
 * struct TreeNode {
 *     int val;
 *     TreeNode *left;
 *     TreeNode *right;
 *     TreeNode() : val(0), left(nullptr), right(nullptr) {}
 *     TreeNode(int x) : val(x), left(nullptr), right(nullptr) {}
 *     TreeNode(int x, TreeNode *left, TreeNode *right) : val(x), left(left), right(right) {}
 * };
 */
class Solution {
public:
    int getDepth(TreeNode *root) {
        return root == nullptr ? 0 : max(getDepth(root->left), getDepth(root->right)) + 1;
    }

    int diameterOfBinaryTree(TreeNode* root) {

// 最长路径的三种情况
// * 通过根节点
// * 在左子树
// * 在右子树

//          1
//       2    
//     4  5  
//  6 7  8 9
// diameter =  5
        if ( nullptr == root)
            return 0;
        
        int lmx = diameterOfBinaryTree(root->left);
        int rmx = diameterOfBinaryTree(root->right);

        int ans = max(lmx, rmx);
        int ldepth = getDepth(root->left);
        int rdepth = getDepth(root->right);


        return max(ans, ldepth + rdepth); 
    }
};
2.2 动态规划

我们可以在求深度的时候,更新答案,返回经过根节点但不拐弯的链的最长长度。


/**
 * Definition for a binary tree node.
 * struct TreeNode {
 *     int val;
 *     TreeNode *left;
 *     TreeNode *right;
 *     TreeNode() : val(0), left(nullptr), right(nullptr) {}
 *     TreeNode(int x) : val(x), left(nullptr), right(nullptr) {}
 *     TreeNode(int x, TreeNode *left, TreeNode *right) : val(x), left(left), right(right) {}
 * };
 */
class Solution {
public:
    // 自底向上求出,经过当前节点的最大深度
    // 并统计经过当前节点的路径长度
    // 返回经过子树的深度

    int getDepth(TreeNode *root, int &ans) {
        if ( nullptr == root)
            return 0;
        int ldepth = getDepth(root->left, ans);
        int rdepth = getDepth(root->right, ans);

        ans = max( ldepth + rdepth + 1, ans);
        
        return max(ldepth, rdepth) + 1;
    }

    int diameterOfBinaryTree(TreeNode* root) {
        int ans = 0;

        getDepth(root, ans);
        
        return ans - 1;
    }
};
  • 2
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 1
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值