力扣543. 二叉树的直径(java DFS解法)

Problem: 543. 二叉树的直径

文章目录

题目描述

给你一棵二叉树的根节点,返回该树的 直径 。

二叉树的 直径 是指树中任意两个节点之间最长路径的 长度 。这条路径可能经过也可能不经过根节点 root 。

两节点之间路径的 长度 由它们之间边数表示。

思路

本题目要求我们求取二叉树中最长的路径 ,可将其按递归 的思想分解成的最小子问题如下:

1.求取左子树的最长路径

2.求取右子树的最长路径

3.合并求取树的最长路径

解题方法

1.定义成员变量result记录最长"直径"

2.编写递归代码,依次得到左右子树的最长"直径"

3.将左右子树的最长"直径"合并得到当前的最长"直径",并与result比较更新

4.在归的过程中返回当前左右子树的最长路径加一(因为此时要回退到上一个节点,所以要加一!!!)

复杂度

时间复杂度:

O ( n ) O(n) O(n)

空间复杂度:

O ( h ) O(h) O(h) h h h为树的高度

Code

java 复制代码
/**
 * Definition for a binary tree node.
 * public class TreeNode {
 *     int val;
 *     TreeNode left;
 *     TreeNode right;
 *     TreeNode() {}
 *     TreeNode(int val) { this.val = val; }
 *     TreeNode(int val, TreeNode left, TreeNode right) {
 *         this.val = val;
 *         this.left = left;
 *         this.right = right;
 *     }
 * }
 */
class Solution {
    //Recode the longest diameter
    private int result = 0;

    /**
     * Gets the path length between any two nodes of a tree
     *
     * @param root The root node of a tree
     * @return int
     */
    public int diameterOfBinaryTree(TreeNode root) {
        claMaxHeight(root);
        return result;
    }

    /**
     * Recursively gets the longest path containing the root node
     *
     * @param root The root node of a tree
     * @return int
     */
    public int claMaxHeight(TreeNode root) {
        if (root == null) {
            return 0;
        }
        //Gets the longest path of the left and right subtree
        int maxLeftHeight = claMaxHeight(root.left);
        int maxRightHeight = claMaxHeight(root.right);
        //Get the longest path("diameter")
        int diameter = maxLeftHeight + maxRightHeight;
        //Update the longest path("diameter")
        if (diameter > result) {
            result = diameter;
        }
        return Math.max(maxLeftHeight, maxRightHeight) + 1;
    }
}
相关推荐
cfm_29146 分钟前
Leaf-segment号段模式
java
Wang's Blog9 分钟前
Java 项目实战: 交友项目 - 发布圈子动态:数据库表和接口文档介绍
java·数据库·交友
paopaokaka_luck9 分钟前
智慧电玩店管理系统(空闲机台随机分配、游玩时长概率模拟、积分自动结算、积分兑换闭环、 ECharts经营分析、 腾讯地图选址)
java·人工智能·mysql·echarts·推荐算法
LMT流氓兔31 分钟前
第五单元——第9课:防止同一次操作重复执行
java·服务器·数据库·算法·ai·langchain
春弦_37 分钟前
LeetCode Hot 100 刷题笔记
笔记·leetcode·哈希算法
OxYGC40 分钟前
Spring 面经系列 · 第 6 篇:Spring MVC 请求全流程、父子容器与零配置原理
java·spring·mvc
code2cat43 分钟前
Java高级篇之JDBC:连接数据库,完成查询、更新与事务
java·开发语言·数据库
bksczm1 小时前
Redis数据结构之string
java·redis·mybatis
cc_瀚海知行1 小时前
资料检索 1|直接放入全文、按需读文件和先检索,有什么区别?
java·人工智能·ai
BioRunYiXue1 小时前
使用docker分析高通量测序数据
java·数据库·人工智能·spring cloud·docker·tomcat·html