题目地址:https://leetcode.com/problems/diameter-of-binary-tree/#/description

题目描述

Given a binary tree, you need to compute 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.

Example:
Given a binary tree

      1
/ \
2 3
/ \
4 5

Return 3, which is the length of the path [4,2,1,3] or [5,2,1,3].

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

题目大意

找出树的两个节点之间的最长距离。

解题方法

递归

这个题当然想到是递归。但是如何递归呢。看叶子节点的左右子树的深度都是0,那么,它的深度是0,一个树的深度是其左右子树的最大值+1。

树总的最大宽度是其左右子树高度的和中的最大值。

求最大距离的过程需要在递归里面写,所以这个步骤比较巧妙,一个递归实现了两个作用。

C++代码如下:

/**
* Definition for a binary tree node.
* struct TreeNode {
* int val;
* TreeNode *left;
* TreeNode *right;
* TreeNode(int x) : val(x), left(NULL), right(NULL) {}
* };
*/
class Solution {
public:
int diameterOfBinaryTree(TreeNode* root) {
if (!root) return 0;
distanceToLeaf(root);
return res - 1;
}
int distanceToLeaf(TreeNode* root) {
if (!root) return 0;
if (m.count(root)) return m[root];
int left = distanceToLeaf(root->left);
int right = distanceToLeaf(root->right);
res = max(left + right + 1, res);
int distance = max(left, right) + 1;
m[root] = distance;
return distance;
}
private:
int res = INT_MIN;
unordered_map<TreeNode*, int> m;
};

Java代码如下:

/**
* Definition for a binary tree node.
* public class TreeNode {
* int val;
* TreeNode left;
* TreeNode right;
* TreeNode(int x) { val = x; }
* }
*/
public class Solution {
int max = 0;
public int diameterOfBinaryTree(TreeNode root) {
DeepOfTree(root);
return max;
}
public int DeepOfTree(TreeNode root){
if(root == null) return 0;
int left = DeepOfTree(root.left);
int right = DeepOfTree(root.right);
max = Math.max(max, left + right);
return Math.max(left, right) + 1;
}
}

Python代码如下:

# Definition for a binary tree node.
# class TreeNode:
# def __init__(self, x):
# self.val = x
# self.left = None
# self.right = None class Solution:
def diameterOfBinaryTree(self, root):
"""
:type root: TreeNode
:rtype: int
"""
if not root:
return 0
self.diameter = 0
self.getDepth(root)
return self.diameter def getDepth(self, root):
if not root:
return 0
left = self.getDepth(root.left)
right = self.getDepth(root.right)
self.diameter = max(self.diameter, left + right)
return 1 + max(left, right)

相似题目

124. Binary Tree Maximum Path Sum

日期

2017 年 4 月 21 日
2018 年 11 月 16 日 —— 又到周五了!
2019 年 9 月 27 日 —— 昨天面快手,竟然是纯刷题

【LeetCode】543. Diameter of Binary Tree 解题报告 (C++&Java&Python)的更多相关文章

  1. LeetCode 543. Diameter of Binary Tree (二叉树的直径)

    Given a binary tree, you need to compute the length of the diameter of the tree. The diameter of a b ...

  2. [leetcode]543. Diameter of Binary Tree二叉树直径

    Given a binary tree, you need to compute the length of the diameter of the tree. The diameter of a b ...

  3. [LeetCode] 543. Diameter of Binary Tree 二叉树的直径

    Given a binary tree, you need to compute the length of the diameter of the tree. The diameter of a b ...

  4. 【LeetCode】235. Lowest Common Ancestor of a Binary Search Tree 解题报告(Java & Python)

    作者: 负雪明烛 id: fuxuemingzhu 个人博客: http://fuxuemingzhu.cn/ 目录 题目描述 题目大意 解题方法 日期 [LeetCode] https://leet ...

  5. 【LeetCode】993. Cousins in Binary Tree 解题报告(C++ & python)

    作者: 负雪明烛 id: fuxuemingzhu 个人博客: http://fuxuemingzhu.cn/ 目录 题目描述 题目大意 解题方法 DFS BFS 日期 题目地址:https://le ...

  6. 【LeetCode】987. Vertical Order Traversal of a Binary Tree 解题报告(C++ & Python)

    作者: 负雪明烛 id: fuxuemingzhu 个人博客: http://fuxuemingzhu.cn/ 目录 题目描述 题目大意 解题方法 DFS BFS 日期 题目地址:https://le ...

  7. 【LeetCode】965. Univalued Binary Tree 解题报告(Python & C++)

    作者: 负雪明烛 id: fuxuemingzhu 个人博客: http://fuxuemingzhu.cn/ 目录 题目描述 题目大意 解题方法 BFS DFS 日期 题目地址:https://le ...

  8. 【LeetCode】108. Convert Sorted Array to Binary Search Tree 解题报告 (Java & Python)

    作者: 负雪明烛 id: fuxuemingzhu 个人博客: http://fuxuemingzhu.cn/ 目录 题目描述 题目大意 解题方法 Java解法 Python解法 日期 题目地址:ht ...

  9. 【LeetCode】654. Maximum Binary Tree 解题报告 (Python&C++)

    作者: 负雪明烛 id: fuxuemingzhu 个人博客:http://fuxuemingzhu.cn/ 目录 题目描述 题目大意 解题方法 递归 日期 题目地址:https://leetcode ...

随机推荐

  1. GWAS初探

    原理 GWAS 的主要方法学依据是归纳法中的共变法,是探究复杂因果关系最主要的科学思维和方法.所谓共变法,是通过考察被研究现象发生变化的若干场合中,确定是否只有一个情况发生相应变化,如果是,那么这个发 ...

  2. R语言与医学统计图形【3】条形图、误差图

    R语言基础绘图系统 基础图形--条形图.误差图 3.条形图 barplot接收的数据是矩阵而非数据框. data <- sample(c(50:80),5) barplot(data,col=h ...

  3. SpringCloud微服务实战——搭建企业级开发框架(三十一):自定义MybatisPlus代码生成器实现前后端代码自动生成

      理想的情况下,代码生成可以节省很多重复且没有技术含量的工作量,并且代码生成可以按照统一的代码规范和格式来生成代码,给日常的代码开发提供很大的帮助.但是,代码生成也有其局限性,当牵涉到复杂的业务逻辑 ...

  4. acknowledge

    accord+knowledge. accord好几个意思,knowledge不遑多让,We gotta acknowledge the word acknowledge has many meani ...

  5. day14 linux三剑客之sed命令

    day14 linux三剑客之sed命令 sed命令 Sed 主要用来自动编辑一个或多个文件.简化对文件的反复操作.编写转换程序等. sed(流式编辑器) : sed主要用来修改文件. 1.sed命令 ...

  6. Ecshop 安装

    参考 http://www.68ecshop.com/article-617.html ecshop的安装第一步:下载ecshop网店系统正式版安装包 我们可以来ecshop开发中心的官网(www.6 ...

  7. 【leetcode】153. Find Minimum in Rotated Sorted Array

    Suppose an array of length n sorted in ascending order is rotated between 1 and n times. For example ...

  8. C++类的定义,成员函数的定义,对象的创建与使用

    类是一个模板,可用类生成一系列可用的实例.例如 int B就是生成了一个符合int的数据B,类也是一样,使用类名就可以直接生成一个实例, 该实例中包含类中所有的数据类型和对这些数据的操作方法. 首先, ...

  9. ubantu上编辑windows程序

    命令简记 cd $GOROOT/src cp -r $GOROOT /root/go1.4 CGO_ENABLED=0 GOOS=windows GOARCH=amd64 ./make.bash 操作 ...

  10. mysql触发器实例说明

    触发器是一类特殊的事务 ,可以监视某种数据操作(insert/update/delete),并触发相关操作(insert/update/delete). 看以下事件: 完成下单与减少库存的逻辑 Ins ...