[LeetCode] 543. Diameter of Binary Tree

Given the root of a binary tree, return 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.

The length of a path between two nodes is represented by the number of edges between them.

Example 1:
Example 1
Input: root = [1,2,3,4,5]
Output: 3
Explanation: 3 is the length of the path [4,2,1,3] or [5,2,1,3].

Example 2:
Input: root = [1,2]
Output: 1

Constraints:
The number of nodes in the tree is in the range [1, 104].
-100 <= Node.val <= 100

二叉树的直径。

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

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

来源:力扣(LeetCode)
链接:https://leetcode.cn/problems/diameter-of-binary-tree
著作权归领扣网络所有。商业转载请联系官方授权,非商业转载请注明出处。

思路

题意是给一个二叉树,找二叉树里面的最大直径。最大直径的定义是任意两个 node 之间的最大距离。注意这个最大距离很有可能不经过根节点,如下图例子,最大直径是从 9 到 8,摘自LC中文网。
Example

思路是后序遍历 postorder。做法类似104题找二叉树最大深度用到的递归,但是稍微做一点改动。设置一个全局变量记录 res 这个最大长度,递归函数找的依然是最大深度但是 res 记录的是经过当前节点的 diameter。helper 函数往父节点 return 的则是一边的最长长度 + 1 = 一边的最长长度 + 当前这个子节点到父节点的距离。

照着这个例子跑一下吧,比如根节点的左孩子 2 这里。此时我需要知道的信息是经过 2 的 diameter 最长可以到多少,所以是 left + right。但是我往 2 的父节点 1 需要 return 的信息是经过 2(同时也经过1)的最长的 diameter,我能贡献的长度是多少。这个长度是 2 的左右子树能贡献出来的较长者 + 1(2到1的距离)。

复杂度

时间O(n)
空间O(n)

代码

Java实现

/**
 * Definition for a binary tree node.
 * public class TreeNode {
 *     int val;
 *     TreeNode left;
 *     TreeNode right;
 *     TreeNode(int x) { val = x; }
 * }
 */
class Solution {
    int res = 0;

    public int diameterOfBinaryTree(TreeNode root) {
        helper(root);
        return res;
    }

    private int helper(TreeNode root) {
        // base case
        if (root == null) {
            return 0;
        }
        int left = helper(root.left);
        int right = helper(root.right);
        // 经过当前节点的直径是多长
        res = Math.max(res, left + right);
        // 但是往父节点return的时候,return的却是一边的最长长度 + 1 = 一边的最长长度 + 子节点到父节点的距离
        return Math.max(left, right) + 1;
    }
}

相关题目

104. Maximum Depth of Binary Tree
110. Balanced Binary Tree
366. Find Leaves of Binary Tree
543. Diameter of Binary Tree
1522. Diameter of N-Ary Tree
1245. Tree Diameter
posted @ 2020-03-18 01:58  CNoodle  阅读(284)  评论(0编辑  收藏  举报