​LeetCode刷题实战543:二叉树的直径

算法的重要性,我就不多说了吧,想去大厂,就必须要经过基础知识和业务逻辑面试+算法面试。所以,为了提高大家的算法能力,这个公众号后续每天带大家做一道算法题,题目就从LeetCode上面选 !

今天和大家聊的问题叫做 二叉树的直径,我们先来看题面:

https://leetcode-cn.com/problems/diameter-of-binary-tree/

Given the root of a binary tree, return the length of the diameter of the tree.

The diameter of a binary tree is the length of the longest path between any two nodes in a tree. This path may or may not pass through the root.

The length of a path between two nodes is represented by the number of edges between them.

给定一棵二叉树,你需要计算它的直径长度。一棵二叉树的直径长度是任意两个结点路径长度中的最大值。这条路径可能穿过也可能不穿过根结点。

示例                         

947dd803cfff060305b811af0bd51726.png

解题

思路一:不一定最长路径一定要穿过根节点,所以每个节点都要遍历,把每个节点作为根节点,然后,算出根节点左子树的最大深度和右子树的最大深度,把把左右子树的最大深度加起来,作为暂时当前根节点的最大路径长度。把所有节点作为根节点,比较所有根节点的最大路径长度,选最大的。

class Solution {
public:
  int md, td;
  int diameterOfBinaryTree(TreeNode* root) {
    if (!root)
      return 0;
    md = td = 0;
    preOrder(root);
    return md;
  }
  int maxDepth(TreeNode *root)//计算每个节点(根节点)的左右子树最大深度
  {
    if (!root)
      return 0;
    if (root->left == NULL && root->right == NULL)
      return 1;
    else if (!root->left)
      return maxDepth(root->right)+1;
    else if (!root->right)
      return maxDepth(root->left)+1;
    else
      return max(maxDepth(root->left), maxDepth(root->right))+1;
 
  }
  void preOrder(TreeNode *root)//遍历每个节点,把遍历到的每个节点作为根节点
  {
    if (!root)
      return;
    td= maxDepth(root->left) + maxDepth(root->right);
    md = max(md, td);
    preOrder(root->left);
    preOrder(root->right);
  }
};

思路二:利用递归,对每一个根节点,计算其左边的深度和右边的深度,左右深度相加即为当前子树的直径,遍历完每一棵子树后最大的那个直径即为二叉树的直径。

class Solution {
public:
    int diameterOfBinaryTree(TreeNode* root) {
        int res=0;
        depth(root,res);
        return res;
    }
private:
    int depth(TreeNode *root,int &res){
        if (!root) return 0;
        int left_depth=depth(root->left,res);
        int right_depth=depth(root->right,res);
        res=max(res,right_depth+left_depth);
        return max(left_depth+1,right_depth+1);
    }
};

好了,今天的文章就到这里,如果觉得有所收获,请顺手点个在看或者转发吧,你们的支持是我最大的动力 。

上期推文:

LeetCode1-540题汇总,希望对你有点帮助!

LeetCode刷题实战541:反转字符串 II

LeetCode刷题实战542:01 矩阵

1c2f1723e951ec87baa3e9efdd8cd8a4.png

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

程序员小猿666

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值