二叉树的直径 2025-08-19 作者 Y Y 1269 字 本文最后编辑于 前,其中的内容可能需要更新。 二叉树的直径 题目 123456789101112给你一棵二叉树的根节点,返回该树的 直径 二叉树的 直径 是指树中任意两个节点之间最长路径的 长度 这条路径可能经过也可能不经过根节点 root 两节点之间路径的 长度 由它们之间边数表示示例 1:输入:root = [1,2,3,4,5]输出:3解释:3 ,取路径 [4,2,1,3] 或 [5,2,1,3] 的长度示例 2:输入:root = [1,2]输出:1 解法 1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253思路:直径 = 左子树的最大深度和右子树的最大深度, 递归每个节点, 找到最大的直径代码:class TreeNode{ public $val = null; public $left = null; public $right = null; function __construct($val = 0, $left = null, $right = null) { $this->val = $val; $this->left = $left; $this->right = $right; }}private $ans;/** * @param TreeNode $root * * @return Integer */function diameterOfBinaryTree($root){ if (!$root->left && !$root->right) { return 0; } $this->ans = 1; $this->depth($root); return $this->ans;}private function depth($node){ if (!$node) { return 0; } // 左子树的最大深度 $left = $this->depth($node->left); // 右子树的最大深度 $right = $this->depth($node->right); // 最大直径 = 左子树最大深度 + 右子树最大深度 $this->ans = max($this->ans, $left + $right); // 左右子树较大一边的深度+1 = 当前节点的最大深度 return max($left, $right) + 1;} < 上一篇 下一篇 >