Given a binary tree, find the maximum path sum.
The path may start and end at any node in the tree.
For example:
Given the below binary tree,
1
/ \
2 3
Return6.
在二叉树中找一条路径,这条路径的和最大。
解题思路:
深度遍历所有节点,获取每个节点是否是最大值,并且获取这个节点下的最大路径,来给上一层节点使用
注意这个题目的线路的开始结束两个节点是任意两个节点!!!
<?php
class Node {
public $val;
public $left = null;
public $right = null;
public function __construct($val) {
$this->val = $val;
}
}
class Solution {
public function maxPathSum($root, &$max) {
if ($root == null) {
return 0;
}
$leftVal = $this->maxPathSum($root->left, $max);
$rightVal = $this->maxPathSum($root->right, $max);
//把这个节点下比较大的一条线路返回回去
$maxChildVal = $leftVal > $rightVal ? $leftVal : $rightVal;
$tmp = $root->val;
if ($leftVal > 0) {
$tmp += $leftVal;
}
if ($rightVal > 0) {
$tmp += $rightVal;
}
if ($tmp > $max) {
$max = $tmp;
}
return $maxChildVal > 0 ? $maxChildVal + $root->val : $root->val;
}
}
$node1 = new Node(1);
$node2 = new Node(2);
$node3 = new Node(3);
$node4 = new Node(4);
$node1->left = $node2;
$node1->right = $node3;
$node2->left = $node4;
$obj = new Solution();
$max = $node1->val;
$ret = $obj->maxPathSum($node1, $max);
print $max;