题目地址: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. python 新闻管理系统——启示

    mysql取整函数: mysql函数ceil.floor.round mysql 取整 1.ceil() / ceiling() 向上取整 ex: ceil(1.2) = 2 2.floor() 向下 ...

  2. 53-Linked List Cycle II

    Linked List Cycle II My Submissions QuestionEditorial Solution Total Accepted: 74093 Total Submissio ...

  3. 使用systemd将iptables规则在docker启动后自动导入

    编写systemd文件 $ sudo vi /etc/systemd/system/iptables-import.service # /etc/systemd/system/iptables-imp ...

  4. 🏆【Alibaba中间件技术系列】「Sentinel技术专题」分布式系统的流量防卫兵的基本介绍(入门源码介绍)

    推荐资料 官方文档 官方demo Sentinel 是什么? 随着微服务的流行,服务和服务之间的稳定性变得越来越重要.Sentinel 以流量为切入点,从流量控制.熔断降级.系统负载保护等多个维度保护 ...

  5. Spark(一)【spark-3.0安装和入门】

    目录 一.Windows安装 1.安装 2.使用 二.Linux安装 Local模式 1.安装 2.使用 yarn模式 1.安装 2.使用 3.spark的历史服务器集成yarn 一.Windows安 ...

  6. 浏览器相关,关于强缓存、协商缓存、CDN缓存。

    强缓存和协商缓存 在介绍缓存的时候,我们习惯将缓存分为强缓存和协商缓存两种.两者的主要区别是使用本地缓存的时候,是否需要向服务器验证本地缓存是否依旧有效. 顾名思义,协商缓存,就是需要和服务器进行协商 ...

  7. Android项目的settings.gradle和build.gradle

    gradle构建的项目中的build.gradle和settings.gradle文件 build.gradle 浅析(一) 史上最全的Android build.gradle配置教程 Android ...

  8. Lottie 使用

    原文:https://mp.weixin.qq.com/s?__biz=MzIxNjc0ODExMA==&mid=2247485033&idx=1&sn=54dd477b4c4 ...

  9. 【并发编程】Java并发编程-看懂AQS的前世今生

    在我们可以深入学习AbstractQueuedSynchronizer(AQS)之前,必须具备了volatile.CAS和模板方法设计模式的知识,本文主要想从AQS的产生背景.设计和结构.源代码实现及 ...

  10. my43_mysql内存相关概念

    相关参数 read_buffer_size https://dev.mysql.com/doc/refman/8.0/en/server-system-variables.html#sysvar_re ...