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


    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
        }
    }
    
  • 相关阅读:
    wp8 入门到精通
    C# 从入门到精通
    wp8 json2csharp
    wp8 安装.Net3.5
    delphi资源文件制作及使用详解
    delphi弹出选择对话框选择目录SelectDirectory 函数
    delphi 判断WIN8 , WIN8.1 , WIN10 系统版本
    外壳扩展创建快捷方式和获取快捷方式的目标对象
    文本究竟是使用哪种字
    用Delphi创建服务程序
  • 原文地址:https://www.cnblogs.com/zhongju/p/13812807.html
Copyright © 2020-2023  润新知