543、二叉树的直径

  1. 543、二叉树的直径
    1. 示例 :
  2. 题解
    1. 1、递归求深度中,更新最大值

543、二叉树的直径

给定一棵二叉树,你需要计算它的直径长度。一棵二叉树的直径长度是任意两个结点路径长度中的最大值。这条路径可能穿过根结点。

示例 :

给定二叉树

          1
         / \
        2   3
       / \     
      4   5    
返回 3, 它的长度是路径 [4,2,1,3] 或者 [5,2,1,3]。

注意:两结点之间的路径长度是以它们之间边的数目表示。

链接:https://leetcode-cn.com/problems/diameter-of-binary-tree

题解

此题是:求二叉树的深度的变形。
本题的“直径“是指:对于一颗二叉树的每一个节点,求其左右子树深度之和的最大值。

1、递归求深度中,更新最大值

/**
 * Definition for a binary tree node.
 * public class TreeNode {
 *     int val;
 *     TreeNode left;
 *     TreeNode right;
 *     TreeNode(int x) { val = x; }
 * }
 */
class Solution {
    int maxLen = 0;
    public int diameterOfBinaryTree(TreeNode root) {
        if (root == null) {
            return 0;
        }
        // 求深度
        treeDepth(root);
        return maxLen;   
    }

    public int treeDepth(TreeNode root) {
        if (root == null) {
            return 0;
        }
        // 递归求左子树的深度
        int left = treeDepth(root.left);
        // 递归求右子树的深度
        int right = treeDepth(root.right);
        // 更新最大直径
        if (maxLen < left + right) {
            maxLen = left + right;
        }
        return left > right ? left + 1: right + 1;
    }
}

转载请注明来源,欢迎对文章中的引用来源进行考证,欢迎指出任何有错误或不够清晰的表达。可以在下面评论区评论,也可以邮件至 1056615746@qq.com

💰

Title:543、二叉树的直径

Count:308

Author:攀登

Created At:2020-07-26, 00:19:44

Updated At:2024-06-15, 15:52:32

Url:http://jiafeimao-gjf.github.io/2020/07/26/543%E3%80%81%E4%BA%8C%E5%8F%89%E6%A0%91%E7%9A%84%E7%9B%B4%E5%BE%84/

Copyright: 'Attribution-non-commercial-shared in the same way 4.0' Reprint please keep the original link and author.

×

Help us with donation