题目地址: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. python13各种器

    def hello(): print("hello") def test(): print("test") def hello_wrapper(): print ...

  2. java 按内容拆分文件

    文件内容为: BC************* **************** *************** BC************* **************** *********** ...

  3. Oracle-with c as (select ......) 实现多次调用子查询结果

    with c as  (select a.trandt,sum(a.tranam) tranam from tran a group by a.trandt )   #将子查询抽取出来,以后可以直接重 ...

  4. EXCEL如何用公式提取一列中的唯一值和不重复值

    说明:思路用的很新奇,也对COUNTIF有了更深一步的了解,但是,对于百行数据运算速度特别低,不适合数据多的使用 当面对一堆数据,我们要提取一列的唯一值的时候,如果单纯用人为一个个判断,显然是不科学的 ...

  5. 『学了就忘』Linux文件系统管理 — 67、通过命令模式进行LVM分区

    目录 1.物理卷管理 (1)准备硬盘或者分区 (2)建立物理卷 (3)查看物理卷 (3)删除物理卷 2.创建卷组 (1)建立卷组 (2)查看卷组 (3)增加卷组容量 (4)减小卷组容量 (5)删除卷组 ...

  6. postgresql安装部署

    一.下载安装: 1.下载: 官网下载地址:https://www.postgresql.org/download/linux/redhat/ 也可以用这个:https://www.enterprise ...

  7. 大数据学习day18----第三阶段spark01--------0.前言(分布式运算框架的核心思想,MR与Spark的比较,spark可以怎么运行,spark提交到spark集群的方式)1. spark(standalone模式)的安装 2. Spark各个角色的功能 3.SparkShell的使用,spark编程入门(wordcount案例)

    0.前言 0.1  分布式运算框架的核心思想(此处以MR运行在yarn上为例)  提交job时,resourcemanager(图中写成了master)会根据数据的量以及工作的复杂度,解析工作量,从而 ...

  8. 100个Shell脚本——【脚本5】数字求和

    [脚本5]数字求和 编写shell脚本,要求输入一个数字,然后计算出从1到输入数字的和,要求,如果输入的数字小于1,则重新输入,直到输入正确的数字为止,示例: 一.脚本 #!/bin/bash whi ...

  9. Android Https相关完全解析

    转载: 转载请标明出处: http://blog.csdn.net/lmj623565791/article/details/48129405: 本文出自:[张鸿洋的博客] 一.概述 其实这篇文章理论 ...

  10. tableView和tableViewCell的背景颜色问题

    当在tableView中添加cell数据时,我们会发现原本设置的tableView的背景颜色不见了,这是因为加载cell数据时,tableView的背景颜色被cell数据遮盖住了,此时,可以通过设置c ...