题目地址: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. FFmpeg笔记:使用MSVC工具链编译Windows版本静态库、动态库

    2019年3月开始,为了将音视频编解码功能集成到Cocos2d-x中,开始接触到FFmpeg: 当时开发环境还在Mac下,编译FFmpeg相比现在用Windows平台要方便的多: 最近,公司内部有个U ...

  2. c#GridView

    分页: 1.先把属性AllowPaging设置为true, 2.pagesize为每一页的行数,PageSize="15". 3.OnPageIndexChanging=" ...

  3. 线性表A,B顺序存储合并

    线性表A,B顺序存储合并 有两张非递增有序的线性表A,B,采用顺序存储结构,两张表合并用c表存,要求C为非递减有序的,然后删除C表中值相同的多余元素.元素类型为整型 输入格式: 第一行输入输入表A的各 ...

  4. java加密方式

    加密,是以某种特殊的算法改变原有的信息数据,使得未授权的用户即使获得了已加密的信息,但因不知解密的方法,仍然无法了解信息的内容.大体上分为双向加密和单向加密,而双向加密又分为对称加密和非对称加密(有些 ...

  5. maven常用Java配置

    maven国内镜像 ------------------------------------------------------------------------------------------ ...

  6. lambda表达式快速创建

    Java 8十个lambda表达式案例 1. 实现Runnable线程案例 使用() -> {} 替代匿名类: //Before Java 8: new Thread(new Runnable( ...

  7. Linux系统的负载与CPU、内存、硬盘、用户数监控的shell脚本

    利用Shell脚本来监控Linux系统的负载.CPU.内存.硬盘.用户登录数. 这几天在学习研究shell脚本,写的一些系统负载.CPU.内存.硬盘.用户数监控脚本程序.在没有nagios监控的情况下 ...

  8. Maven错误收集

    Eclipse 创建项目时报错 Could not resolve archetype org.apache.maven.archetypes:maven-archetype-quickstart:1 ...

  9. jQuery - focusin/focusout/focus/blur事件的区别与不同

    focus与blur事件:不支持冒泡 focusin与focusout:支持冒泡 事件触发顺序: 对于同时支持这4个事件的浏览器,事件执行顺序为focusin(聚焦) > focus > ...

  10. spring的核心容器ApplicationContext

    //bean.xml配置文件 <?xml version="1.0" encoding="UTF-8"?><beans xmlns=" ...