<?php
/**
* Definition for a binary tree node.
* 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;
* }
* }
*/
class Solution {
private $maxPath = PHP_INT_MIN;
/**
* 后序遍历,对于某个结点为根的路径而言,其路径的最大值为 maxLeft(0 if maxLeft < 0) + maxRight(0 if maxRight < 0) + node->val
* 整个二叉树的最大路径,就是这些路径的最大值
* 而某个结点的路径贡献最大值为 max(maxleft+nodeval, maxright+nodeval);
* @param TreeNode $root
* @return Integer
*/
function maxPathSum($root) {
$this->findMaxPath($root);
return $this->maxPath;
}
function findMaxPath($root) {
if (is_null($root)) {
return 0;
}
$maxLeft = max($this->findMaxPath($root->left), 0);
$maxRight = max($this->findMaxPath($root->right), 0);
// 某个结点的路径贡献值
$pathValue = max($maxLeft + $root->val, $maxRight + $root->val);
// 以该结点为根的路径总长度
$totalValue = $maxLeft + $root->val + $maxRight;
$this->maxPath = max($this->maxPath, $totalValue);
return $pathValue;
}
}
结果: