力扣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;
    }
}
相关推荐
码智社9 小时前
Redis 哨兵模式详解:从原理到生产实践
java·redis
救救孩子把9 小时前
结构化输出为何“格式正确、答案错误”?JSON Schema 的能力边界
android·java·json·agent·agent服务
silvamux_9 小时前
微头条爆款体平台适配实测:把交付要求变成可计算的指标
java·线性代数·算法·决策树·矩阵
论文复现现场9 小时前
DeepSeek V4.1 Flash 和 V4 Pro 有什么区别?API 价格、性能与迁移建议
java·服务器·人工智能·python·大模型api·deepseek·deepseek v4.1
郭小李9 小时前
转发与重定向
java·服务器·数据库
你看我名字9 小时前
数眼智能 Search + Reader 实战:联网问答怎样避免“搜到了,却引用错了”
android·java·开发语言
重生之小比特9 小时前
【算法拾光】前缀和|连续的子数组和 + 和相同的二元子数组
算法·leetcode·哈希算法
Pniubi10 小时前
力扣 102二叉树的层序遍历(广度优先搜索)
leetcode·宽度优先
一去不复返的通信er10 小时前
力扣15:盛最多水的容器
算法·leetcode
Navigator_Z10 小时前
LeetCode //C - 1309. Decrypt String from Alphabet to Integer Mapping
c语言·算法·leetcode