当前位置 博文首页 > 文章内容

    [LeetCode] 543. Diameter of Binary Tree(二叉树的直径)

    作者: 栏目:未分类 时间:2020-10-14 9:00:20

    本站于2023年9月4日。收到“大连君*****咨询有限公司”通知
    说我们IIS7站长博客,有一篇博文用了他们的图片。
    要求我们给他们一张图片6000元。要不然法院告我们

    为避免不必要的麻烦,IIS7站长博客,全站内容图片下架、并积极应诉
    博文内容全部不再显示,请需要相关资讯的站长朋友到必应搜索。谢谢!

    另祝:版权碰瓷诈骗团伙,早日弃暗投明。

    相关新闻:借版权之名、行诈骗之实,周某因犯诈骗罪被判处有期徒刑十一年六个月

    叹!百花齐放的时代,渐行渐远!



    Description

    Given a binary tree, you need to compute 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.

    给定一棵二叉树,你需要计算二叉树直径的长度。二叉树的直径是二叉树内任意两节点间路径的最大值。这个路径不一定经过二叉树的根。

    Examples

    Given a binary tree

          1
         / \
        2   3
       / \     
      4   5    
    

    Return 3, which is the length of the path [4,2,1,3] or [5,2,1,3].

    Note

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

    两节点间路径的长度以两节点间经过的边的数量表示。

    Solution

    题目里明说了,二叉树的直径不一定经过 root。二叉树的直径有可能在以下地方出现:

    1. 完全位于左子树

    2. 完全位于右子树

    3. 经过 root(即跨越了左右子树)

    前两种情况比较好处理,递归求解问题即可,需要注意的是第 3 种情况。由于情况 3 要考虑跨越左右子树的情况,所以对左右子问题的求解结果应该只是当直径不跨越 root 的情况(直径若在这之前跨越了子树的 root,父问题就无法求解了),于是需要把最后的结果单独拿出来处理,最后得到如下解答。

    /**
     * Example:
     * var ti = TreeNode(5)
     * var v = ti.`val`
     * Definition for a binary tree node.
     * class TreeNode(var `va`: Int) {
     *     var left: TreeNode? = null
     *     var right: TreeNode? = null
     * }
     */
    import kotlin.math.max
    
    class Solution {
        private var result = 0
    
        fun diameterOfBinaryTree(root: TreeNode?): Int {
            dfs(root)
    
            return result
        }
    
        private fun dfs(root: TreeNode?): Int {
            if (root == null) {
                return 0
            }
            val leftResult = dfs(root.left)
            val rightResult = dfs(root.right)
            // 在这里处理直径跨越 `root` 的情况
            result = max(result, leftResult + rightResult)
            // 递归返回时只返回不跨越 `root` 的情况
            return max(leftResult, rightResult) + 1
        }
    }