<?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;
}
}
结果:

本文介绍了一种使用PHP实现的算法,该算法通过后序遍历的方式找到给定二叉树中的最大路径和。最大路径可以是经过根节点的任意路径,也可以是不经过根节点的路径的一部分。


7292

被折叠的 条评论
为什么被折叠?



