<?phpClass TreeNode { /** @var int $val */ public $val = 0; /** @var TreeNode $left */ public $left; /** @var TreeNode $right */ public $right; public function __construct($val) { $this->val = $val; }}class Solution { public $max = 0; public function diameterOfBinaryTree($root) { if ($root == null) return 0; $this->helper($root); return $this->max; } // 取当前节点最大直径 private function helper($root) { $left = ($root->left == null) ? 0 : $this->helper($root->left) + 1; $right = ($root->right == null) ? 0 : $this->helper($root->right) + 1; $this->max = max($this->max, $left + $right); return max($left, $right); }}/** * 4 * / \ * 2 6 * / \ / * 1 3 5 * / * 6 */$tree = new TreeNode(4);$tree->left = new TreeNode(2);$tree->left->left = new TreeNode(1);$tree->left->left->left = new TreeNode(6);$tree->left->right = new TreeNode(3);$tree->right = new TreeNode(6);$tree->right->left = new TreeNode(5);$cls = new Solution();$r = $cls->diameterOfBinaryTree($tree);print_r($r);