• 543. 二叉树的直径


    地址:https://leetcode-cn.com/problems/diameter-of-binary-tree/

    <?php
    /**
    给定一棵二叉树,你需要计算它的直径长度。一棵二叉树的直径长度是任意两个结点路径长度中的最大值。这条路径可能穿过也可能不穿过根结点。
    
     
    
    示例 :
    给定二叉树
    
    1
    / 
    2   3
    / 
    4   5
    返回 3, 它的长度是路径 [4,2,1,3] 或者 [5,2,1,3]。
    
     
    
    注意:两结点之间的路径长度是以它们之间边的数目表示。
    
    来源:力扣(LeetCode)
    链接:https://leetcode-cn.com/problems/diameter-of-binary-tree
    著作权归领扣网络所有。商业转载请联系官方授权,非商业转载请注明出处。
     */
    /**
     * Definition for a binary tree node.
     * class TreeNode {
     *     public $val = null;
     *     public $left = null;
     *     public $right = null;
     *     function __construct($value) { $this->val = $value; }
     * }
     */
    class Solution {
        public $result = 0;
        /**
         * @param TreeNode $root
         * @return Integer
         */
        function diameterOfBinaryTree($root) {
            if($root == null) return 0;
            $this->helper($root);
            return $this->result;
        }
    
        function helper($root){
            $left = $root->left == null ? 0: $this->helper($root->left) +1;
            $right = $root->right == null ? 0 :$this->helper($root->right)+1;
            $this->result = max($this->result,$left+$right);
            return max($left,$right);
        }
    
    }
  • 相关阅读:
    go语言的垮平台编译
    vscode使用技巧
    集合
    泛型
    异常
    Java垃圾回收机制
    java学习笔记9.20
    java变量类型
    目前的学习计划
    离第一篇博客三天
  • 原文地址:https://www.cnblogs.com/8013-cmf/p/12952745.html
Copyright © 2020-2023  润新知