題目
原題地址
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節(jié)點(diǎn)開(kāi)始遍歷所有子節(jié)點(diǎn)杖刷,不走回頭路保證時(shí)間復(fù)雜度為O(n)。最長(zhǎng)路徑可能經(jīng)過(guò)root浴骂,但是也可能是在子節(jié)點(diǎn)中敬肚,所以要有一個(gè)全局變量?jī)?chǔ)存最長(zhǎng)路徑淹魄。
考慮一個(gè)節(jié)點(diǎn):
- 計(jì)算以它開(kāi)始向左或向右的最長(zhǎng)路徑籍铁,作為遞歸返回值傳給父節(jié)點(diǎn)
- 計(jì)算經(jīng)過(guò)它的最長(zhǎng)路徑(可以同時(shí)向左和向右延伸),與全局最長(zhǎng)路徑比較
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) # 從左子節(jié)點(diǎn)開(kāi)始的最長(zhǎng)路徑
num2 = self.search(node.right) # 從右子節(jié)點(diǎn)開(kāi)始的最長(zhǎng)路徑
if node.left and node.left.val == node.val:
num1 += 1 # 左子節(jié)點(diǎn)和節(jié)點(diǎn)值相同浑玛,從左子節(jié)點(diǎn)開(kāi)始的最長(zhǎng)路徑也包含了本節(jié)點(diǎn)绍申,所以+1
else:
num1 = 0 # 如果節(jié)點(diǎn)和左子節(jié)點(diǎn)值不同,從這個(gè)節(jié)點(diǎn)向左的路徑長(zhǎng)度就是0
if node.right and node.right.val == node.val:
num2 += 1
else:
num2 = 0
self.longest = max(self.longest, num1 + num2) # 經(jīng)過(guò)此節(jié)點(diǎn)的最長(zhǎng)路徑與全局最長(zhǎng)路徑比較
return max(num1, num2) # 返回從此節(jié)點(diǎn)開(kāi)始的最長(zhǎng)路徑
def longestUnivaluePath(self, root):
"""
:type root: TreeNode
:rtype: int
"""
self.longest = 0 # 全局最長(zhǎng)路徑
self.search(root)
return self.longest