美文网首页
[LeetCode] Longest Univalue Path

[LeetCode] Longest Univalue Path

作者: lyy0905 | 来源:发表于2018-03-02 14:39 被阅读0次

    题目

    原题地址
    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.

    思路

    用递归解决,从root节点开始遍历所有子节点,不走回头路保证时间复杂度为O(n)。最长路径可能经过root,但是也可能是在子节点中,所以要有一个全局变量储存最长路径。

    考虑一个节点:

    1. 计算以它开始向左或向右的最长路径,作为递归返回值传给父节点
    2. 计算经过它的最长路径(可以同时向左和向右延伸),与全局最长路径比较

    python代码

    # Definition for a binary tree node.
    # class TreeNode(object):
    #     def __init__(self, x):
    #         self.val = x
    #         self.left = None
    #         self.right = None
    
    class Solution(object):
        def search(self, node):
            if node == None:
                return 0
            num1 = self.search(node.left) # 从左子节点开始的最长路径
            num2 = self.search(node.right) # 从右子节点开始的最长路径
            if node.left and node.left.val == node.val:
                num1 += 1 # 左子节点和节点值相同,从左子节点开始的最长路径也包含了本节点,所以+1
            else:
                num1 = 0 # 如果节点和左子节点值不同,从这个节点向左的路径长度就是0
            if node.right and node.right.val == node.val:
                num2 += 1
            else:
                num2 = 0 
            self.longest = max(self.longest, num1 + num2) # 经过此节点的最长路径与全局最长路径比较
            return max(num1, num2) # 返回从此节点开始的最长路径
            
        def longestUnivaluePath(self, root):
            """
            :type root: TreeNode
            :rtype: int
            """
            self.longest = 0 # 全局最长路径
            self.search(root)
            return self.longest
    

    相关文章

      网友评论

          本文标题:[LeetCode] Longest Univalue Path

          本文链接:https://www.haomeiwen.com/subject/sqtaxftx.html