返回介绍

Diameter of a Binary Tree

发布于 2025-02-22 13:01:29 字数 2475 浏览 0 评论 0 收藏 0

Source

The diameter of a tree (sometimes called the width) is the number of nodes
on the longest path between two leaves in the tree.
The diagram below shows two trees each with diameter nine,
the leaves that form the ends of a longest path are shaded
(note that there is more than one path in each tree of length nine,
but no path longer than nine nodes).

Diameter of a Binary Tree

题解

和题 Lowest Common Ancestor 分析思路特别接近。

Java

class TreeNode {
  int val;
  TreeNode left, right;
  TreeNode(int val) {
    this.val = val;
    this.left = null;
    this.right = null;
  }
}

public class Solution {
  public int diameter(TreeNode root) {
    if (root == null) return 0;

    // left, right height
    int leftHight = getHeight(root.left);
    int rightHight = getHeight(root.right);

    // left, right subtree diameter
    int leftDia = diameter(root.left);
    int rightDia = diameter(root.right);

    int maxSubDia = Math.max(leftDia, rightDia);
    return Math.max(maxSubDia, leftHight + 1 + rightHight);
  }

  private int getHeight(TreeNode root) {
    if (root == null) return 0;

    return 1 + Math.max(getHeight(root.left), getHeight(root.right));
  }

  public static void main(String[] args) {
    TreeNode root = new TreeNode(1);
    root.left = new TreeNode(2);
    root.right = new TreeNode(3);
    root.left.left = new TreeNode(4);
    root.left.right = new TreeNode(5);
    root.left.right.left = new TreeNode(6);
    root.left.right.left.right = new TreeNode(7);
    root.left.left.left = new TreeNode(8);

    Solution sol = new Solution();
    int maxDistance = sol.diameter(root);
    System.out.println("Max Distance: " + maxDistance);
  }
}

Reference

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。
列表为空,暂无数据
    我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
    原文