[LeetCode] Longest Univalue Path

题目

原题地址
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
©著作权归作者所有,转载或内容合作请联系作者
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。

推荐阅读更多精彩内容

  • rljs by sennchi Timeline of History Part One The Cognitiv...
    sennchi阅读 7,438评论 0 10
  • 背景 一年多以前我在知乎上答了有关LeetCode的问题, 分享了一些自己做题目的经验。 张土汪:刷leetcod...
    土汪阅读 12,769评论 0 33
  • 感谢上天 张书云(秋水伊人) 他在迷人的音乐声中静静地睡着了, 我不敢开客厅的灯光, 怕他半夜醒来, 摔倒在地。 ...
    qiushui__lianli阅读 161评论 3 4
  • 今天是情人节,非洋人的,而是大中华传统的,七夕情人节。 每年的2.14是西洋的情人节,在节前几天乃至节日当天,看吧...
    烦人的昵称阅读 225评论 0 1
  • 王柏林 公司: 都江堰佳音英语 【日精进打卡第97天】 【知~学习】 《六项精进》 《大学》 【名句】 认为不行的...
    berlin_eda3阅读 147评论 0 0