LeetCode:687. Longest Univalue Path - Python

题目描述:

Given a binary tree, find the length of the longest path where each node in the path has the same value. This path may or may not pass through the root.

Note: The length of path between two nodes is represented by the number of edges between them.

Example 1:

Input:

              5
             / \
            4   5
           / \   \
          1   1   5

Output:

2

Example 2:

Input:

              1
             / \
            4   5
           / \   \
          4   4   5

Output:

2

Note: The given binary tree has not more than 10000 nodes. The height of the tree is not more than 1000.

问题分析:

先解释一下题目,就是让我们找到一个路径,这个路径上面的值都相同,而且可以不经过根节点,例如,例2中的4-4-4这样的。这也是为什么要总结的原因,因为一开始没看懂哈。可以使用递归来做,首先,求出以每个节点为根节点的最长路径,然后从底向上,判断与父亲节点的值是否相同,如果相同,就把当前结点最长的一个分支路径加上1返回给父节点。其中,可以把最长路径保存到一个全局变量中。

Python3实现:

# @Time   :2018/6/25
# @Author :LiuYinxing
# 解题思路 深度优先,递归


class TreeNode:
    def __init__(self, x):
        self.val = x
        self.left = None
        self.right = None


class Solution:
    def __init__(self):
        self.re = 0  # 用于记录每个节点的最长路径

    def longestUnivaluePath(self, root):
        def f(root, n):
            if root == None: return 0
            left = f(root.left, root.val)  # 获取左分支节点与当前节点的最长路径
            right = f(root.right, root.val)  # 获取右分支节点与当前节点的最长路径
            self.re = max(self.re, left + right)  # 获取当前节点的最长路径,并更新记录
            return max(left, right) + 1 if root.val == n else 0  # 当前节点与父节点的值是否相同,如果相同就在子节点加一

        f(root, 0)
        return self.re
欢迎指正哦

猜你喜欢

转载自blog.csdn.net/xx_123_1_rj/article/details/80797237