PHP-最长同值路径

最长同值路径

题意

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

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

示例 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 

你可能感兴趣的:(PHP-最长同值路径)