【Leetcode 687】递归求最大相同路径

版权声明:本文为博主原创文章,未经博主允许不得转载。 https://blog.csdn.net/u011240016/article/details/83070792

类型:Easy, 递归

题目描述:

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

# Definition for a binary tree node.
# class TreeNode:
#     def __init__(self, x):
#         self.val = x
#         self.left = None
#         self.right = None

class Solution:
    def longestUnivaluePath(self, root):
        """
        :type root: TreeNode
        :rtype: int
        """
        self.max_path = 0
        if root == None:
            return 0
        self.recursive_find(root)
        return self.max_path
    
    def recursive_find(self,root):
        if root == None:
            return 0
        left = self.recursive_find(root.left)
        right = self.recursive_find(root.right)
        if (root.left != None and root.val == root.left.val):
            left +=  1
        elif (root.left != None): # 只是非空
            left = 0
        if (root.right != None and root.val == root.right.val):
            right += 1
        elif (root.right != None):
            right = 0
        if left + right > self.max_path:
            self.max_path = left + right
            
        return max(left, right)

能用递归解决问题的,一定是自顶向下。
那么这个问题也是,站在当前结点上思考,左子树的最长路径已经知道了,右子树的最大路径也已经知道了。那么,现在需要做的决策是,结合当前结点值,如何更新最大的路径长度 。用left标记左子树的最大路径长度,right标记右子树的最大路径长度。

第一种情况,左子树非空,且左子树的根结点与当前结点值相同,那么left+1;否则,将left置为0,因为现在考虑的是对max_path是否增量更新。另外一种担忧是,最长路径不一定经过根结点,为什么判断的子树根结点和当前结点值相同时就可以加1呢?这个要从递归会递归到终结退出条件来思考,逐层向上展开。

同样的,右子树思考路径对称过去即可。

现在开始更新最大路径,left + right > max_path吗?

如果当前结点的值与左子树根结点值,右子树结点值都相同,那么left自增1,右子树自增1,合起来最长路径增加2.

如果只有一个子树的根结点值与当前结点值相同,则只有单边子树自增1,另外一个子树的大小置为0。

END.

猜你喜欢

转载自blog.csdn.net/u011240016/article/details/83070792