php路径长度,PHP-最长同值路径

94a84fa0f5dc

最长同值路径

题意

给定一个二叉树,找到最长的路径,这个路径中的每个节点具有相同值。 这条路径可以经过也可以不经过根节点。

注意:两个节点之间的路径长度由它们之间的边数表示。

示例 1:

5

/ \

4 5

/ \ \

1 1 5

输出

2

1

/ \

4 5

/ \ \

4 4 5

输出

2

解题代码

/**

* Definition for a binary tree node.

* class TreeNode {

* public $val = null;

* public $left = null;

* public $right = null;

* function __construct($value) { $this->val = $value; }

* }

*/

class Solution {

public $maxPath;

/**

* @param TreeNode $root

* @return Integer

*/

function longestUnivaluePath($root) {

if($root == null){

return 0;

}

$this->getMaxPath($root);

return empty($this->maxPath) ? 0 : $this->maxPath;

}

public function getMaxPath($head)

{

$leftPath = 0;

$rightPath = 0;

if ($head->left) {

$leftPath = $this->getMaxPath($head->left);

$leftPath = ($head->val == $head->left->val) ? $leftPath + 1 : 0;

}

if ($head->right) {

$rightPath = $this->getMaxPath($head->right);

$rightPath = ($head->val == $head->right->val) ? $rightPath + 1 : 0;

}

$this->maxPath = max($this->maxPath, $leftPath + $rightPath);

return max($leftPath, $rightPath);

}

}

测试

$head = new TreeNode(1);

$head->left = new TreeNode(4);

$head->right = new TreeNode(5);

$head->left->left = new TreeNode(4);

$head->left->right = new TreeNode(4);

$head->right->right = new TreeNode(5);

print_r((new Solution())->longestUnivaluePath($head)); //输出 2

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值