Loading [MathJax]/jax/output/CommonHTML/config.js
前往小程序,Get更优阅读体验!
立即前往
首页
学习
活动
专区
圈层
工具
发布
首页
学习
活动
专区
圈层
工具
MCP广场
社区首页 >专栏 >LeetCode 543. Diameter of Binary Tree

LeetCode 543. Diameter of Binary Tree

原创
作者头像
大学里的混子
修改于 2018-10-30 07:02:07
修改于 2018-10-30 07:02:07
62800
代码可运行
举报
文章被收录于专栏:LeetCodeLeetCode
运行总次数:0
代码可运行

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 binary tree is the length of the longestpath between any two nodes in a tree. This path may or may not pass through the root.

Example: Given a binary tree

代码语言:javascript
代码运行次数:0
运行
AI代码解释
复制
          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.

题目大意:求一个二叉树中的任意两个节点的最长路径

解法一:

直接但是效率地下的解法,我们首先写一个求二叉树深度的函数depthTree(),求出二叉树的左右深度,依次遍历整个二叉树,就可以求出最大的深度。

代码语言:javascript
代码运行次数:0
运行
AI代码解释
复制
public int diameterOfBinaryTree(TreeNode root) {
   if (root==null) return 0;
   return Math.max(depthTree(root.left)+depthTree(root.right),Math.max(diameterOfBinaryTree(root.left),diameterOfBinaryTree(root.right)));
}

public int depthTree(TreeNode root){
    if (root == null) return 0;
    return 1+Math.max(depthTree(root.right),depthTree(root.left));
}

解法二:

这个递归的设计是从下往上遍历二叉树的。left代表沿着root的左孩子的方向的深度,right代表沿着root的右孩子的方向的深度,二者相加就是顶点为root的一条最大路径。

代码语言:javascript
代码运行次数:0
运行
AI代码解释
复制
class Solution {
    int max = 0;
    public int diameterOfBinaryTree(TreeNode root) {
        getDiameter(root);
        return max;
    }
    
    public int getDiameter(TreeNode root) {
        if (root == null) return 0;
        int left = getDiameter(root.left);
        int right = getDiameter(root.right);
        max = Math.max(max, left+right);
        return Math.max(left, right) + 1;  
    }
}

下面将getDiameter()函数加两个输出:

代码语言:javascript
代码运行次数:0
运行
AI代码解释
复制
public int getDiamter(TreeNode root){
    if (root == null) return 0;
    int left = getDiamter(root.left);
    System.out.println(left);
    int right = getDiamter(root.right);
    System.out.println(right);
    max = Math.max(max,left+right);
    return Math.max(left,right)+1;
}

对于一个输入:

代码语言:javascript
代码运行次数:0
运行
AI代码解释
复制
               5
//            / \
//           3   6
//          / \   
//         2   4   
          /
         1 

输出为:

代码语言:javascript
代码运行次数:0
运行
AI代码解释
复制
0
0
1
0
2
0
0
1
3
0
0
1
4

示例:

代码语言:javascript
代码运行次数:0
运行
AI代码解释
复制
         5
        / \
       3   6
      / \   
     2   4   
    / \
   1  null
  /  \
null null   0 0 1 0 2 0 0 1 3 0 0 1 4

这样可以很清楚的看到递归的过程。

不使用全局遍历的写法:

代码语言:javascript
代码运行次数:0
运行
AI代码解释
复制
    public int diameterOfBinaryTree(TreeNode root) {
        int[] res = new int[1];
        getDiamter(root,res);
        return res[0];
    }
    public int getDiamter(TreeNode root,int[] res){
        if (root == null) return 0;
        int left = getDiamter(root.left,res);
        int right = getDiamter(root.right,res);
        res[0] = Math.max(res[0],left+right);
        return Math.max(left,right)+1;
    }

总结:对与二叉树的递归形式有很多,合适的递归方式可以有效的简化算法的复杂度。

原创声明:本文系作者授权腾讯云开发者社区发表,未经许可,不得转载。

如有侵权,请联系 cloudcommunity@tencent.com 删除。

原创声明:本文系作者授权腾讯云开发者社区发表,未经许可,不得转载。

如有侵权,请联系 cloudcommunity@tencent.com 删除。

评论
登录后参与评论
暂无评论
推荐阅读
编辑精选文章
换一批
LeetCode 226 Invert Binary Tree
题意 给予一颗二叉树,返回其每层节点的平均值. 例 : 给予树: 4 / \ 2 7 / \ / \ 1 3 6 9 返回: 4 / \ 7 2 / \ / \ 9 6 3 1 解法 采用深度优先遍历, 从最底层节点开始, 将每个节点的左右节点进行交换即可. /** * Definition for a binary tree node. * public class TreeNode { * i
一份执着✘
2019/12/30
3130
LeetCode笔记:110. Balanced Binary Tree
这道题题目说的太简略了也没有例子,根据不断试错摸出来的情况,就是说每个节点的两个子节点的深度不能想查大于1,比如左子节点下还有子节点,右子节点下没有了,这是允许的,深度相差1,但是如果左子节点的子节点还有子节点,深度相差就是2了,就不平衡了。
Cloudox
2021/11/23
2210
LeetCode笔记:226. Invert Binary Tree
image.png Trivia: Google: 90% of our engineers use the software you wrote (Homebrew), >but you can’t invert a binary tree on a whiteboard so fuck off.
Cloudox
2021/11/23
2520
LeetCode笔记:226. Invert Binary Tree
LintCode 平衡二叉树题目分析代码
给定一个二叉树,确定它是高度平衡的。对于这个问题,一棵高度平衡的二叉树的定义是:一棵二叉树中每个节点的两个子树的深度相差不会超过1。
desperate633
2018/08/22
2270
LintCode 平衡二叉树题目分析代码
Leetcode#104. Maximum Depth of Binary Tree(二叉树的最大深度)
题目描述 给定一个二叉树,找出其最大深度。 二叉树的深度为根节点到最远叶子节点的最长路径上的节点数。 说明: 叶子节点是指没有子节点的节点。 示例: 给定二叉树 [3,9,20,null,null,15,7], 3 / \ 9 20 / \ 15 7 返回它的最大深度 3 。 思路 思路一: 递归 思路二: 非递归,层次遍历 代码实现 package Tree; import java.util.LinkedList; import java.util.Queue
武培轩
2018/09/28
4140
LeetCode 144. Binary Tree Preorder Traversal题目分析代码
Given a binary tree, return the preorder traversal of its nodes' values. For example:Given binary tree {1,#,2,3} , 1 \ 2 / 3
desperate633
2018/08/22
3140
LeetCode 144. Binary Tree Preorder Traversal题目分析代码
LeetCode 114. Flatten Binary Tree to Linked List
关于二叉树的题目,最直接最简单的方法就是采用递归,因为二叉树具有天然的递归结构,实际上二叉树的定义就是用递归的思想来定义的:一个节点的左右子树任然是一个二叉树。
大学里的混子
2018/10/26
3600
LeetCode笔记:104.Maximum Depth of Binary Tree
要探索二叉树的深度,用递归比较方便。我们题目要求的函数返回根节点的深度,那么就做到对二叉树上每个节点调用此函数都返回其作为根节点看待时的深度。比如,所有叶子节点的深度都是1,再往上就是2、3...一直到root根节点的返回值就是最大的深度。 对于每个节点,我们先判断其本身是否是节点,如果是一个空二叉树,那么就应该返回0。 然后,我们定义两个变量,一个左节点深度,一个右节点深度。我们分别判断其有无左节点和右节点,两种节点中的做法都是一样的,假设没有左节点,那么就左节点深度变量就是1,有左节点的话,左节点深度变量就是对左节点调用此函数返回的结果加1;对右节点也做同样的操作。 最后比较左节点深度和右节点深度,判断谁比较大,就返回哪个变量。这样就能一层一层地递归获取最大深度了。
Cloudox
2021/11/23
2290
LeetCode笔记:515. Find Largest Value in Each Tree Row
要找每一行最大的数,我们总归是要遍历二叉树的,遍历二叉树分为BFS和DFS,这里我们要找每行最大的数,那么我们就用BFS,一行行分析过去。
Cloudox
2021/11/23
2370
LeetCode笔记:515. Find Largest Value in Each Tree Row
LeetCode Weekly Contest 24 之 543. Diameter of Binary Tree
第一反映是递归,假设root的左子树以及右子树的diameterOfBinaryTree已经求解出来,那么我们只需要判断一种情况即可,即diameterOfBinaryTree的path并没有经过根节点的情况。
用户1147447
2019/05/26
3810
leetcode543. Diameter of Binary Tree
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.
眯眯眼的猫头鹰
2020/05/12
3410
Leetcod刷题(15)—— 110. 平衡二叉树
解决思路: 1.先写一个能求二叉树深度的方法 2.比较左右子树的深度差是否小于等于1 3.递归求解即可
老马的编程之旅
2022/06/22
1790
​LeetCode刷题实战543:二叉树的直径
算法的重要性,我就不多说了吧,想去大厂,就必须要经过基础知识和业务逻辑面试+算法面试。所以,为了提高大家的算法能力,这个公众号后续每天带大家做一道算法题,题目就从LeetCode上面选 !
程序员小猿
2022/04/12
2320
​LeetCode刷题实战543:二叉树的直径
LeetCode-543-二叉树的直径
给定一棵二叉树,你需要计算它的直径长度。一棵二叉树的直径长度是任意两个结点路径长度中的最大值。这条路径可能穿过也可能不穿过根结点。
benym
2022/07/14
2310
每日三题-验证二叉搜索树、二叉树的直径、把二叉搜索树转换为累加树
👨‍💻个人主页: 才疏学浅的木子 🙇‍♂️ 本人也在学习阶段如若发现问题,请告知非常感谢 🙇‍♂️ 📒 本文来自专栏: 算法 🌈 算法类型:Hot100题 🌈 ❤️ 支持我:👍点赞 🌹收藏 🤟关注 每日三题 验证二叉搜索树 二叉树的直径 把二叉搜索树转换为累加树 验证二叉搜索树 解法一 递归 每次判断cur是否在left与right之间 class Solution { public boolean isValidBST(TreeNode root) {
才疏学浅的木子
2022/11/18
2100
每日三题-验证二叉搜索树、二叉树的直径、把二叉搜索树转换为累加树
LeetCode 662. Maximum Width of Binary Tree
Given a binary tree, write a function to get the maximum width of the given tree. The width of a tree is the maximum width among all levels. The binary tree has the same structure as a full binary tree, but some nodes are null.
大学里的混子
2018/10/29
8460
LeetCode-面试题55-2-平衡二叉树
输入一棵二叉树的根节点,判断该树是不是平衡二叉树。如果某二叉树中任意节点的左右子树的深度相差不超过1,那么它就是一棵平衡二叉树。
benym
2022/07/14
1940
110Balanced Binary Tree
问题:判断二叉树是否为平衡二叉树 分析:树上的任意结点的左右子树高度差不超过1,则为平衡二叉树。          搜索递归,记录i结点的左子树高度h1和右子树高度h2,则i结点的高度为max(h1,h2)=1,|h1-h2|>1则不平衡 c++ /** * Definition for binary tree * struct TreeNode { * int val; * TreeNode *left; * TreeNode *right; * TreeNod
用户1624346
2018/04/17
6160
【算法总结】五道常见的算法-二叉树
前段时间,写了面试必备的一系列文章,反应还不错。有一些读者反馈说,能不能整理一些面试常见的算法。前段时间,我恰好总结了 LeetCode 常见的面试算法题目。
程序员徐公
2022/01/20
1.1K0
【算法总结】五道常见的算法-二叉树
LeetCode 297.Serialize And Deserialize Binary Tree
Serialization is the process of converting a data structure or object into a sequence of bits so that it can be stored in a file or memory buffer, or transmitted across a network connection link to be reconstructed later in the same or another computer environment.
大学里的混子
2018/11/03
4230
相关推荐
LeetCode 226 Invert Binary Tree
更多 >
领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档
本文部分代码块支持一键运行,欢迎体验
本文部分代码块支持一键运行,欢迎体验