1 对于给定的两个节点分别找到它们的最早公共祖先LCA和最近公共祖先LCP。2 计算从LCA到LCP路径上每个节点的传抄次数即为两个节点之间的传抄次数的估计值。这个算法的原理是假设两个节点分别为A和B它们的LCA为CLCP为D。那么从A到B的传抄次数可以拆分成从A到C的传抄次数和从B到D的传抄次数。由于从A到C和从B到D之间没有重叠的节点所以这两个部分的传抄次数可以分别计算。而从C到D的传抄次数可
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 lowestCommonAncestor(self, root, p, q): """ :type root: TreeNode :type p: TreeNode :type q: TreeNode :rtype: TreeNode """ if not root or root == p or root == q: return root left = self.lowestCommonAncestor(root.left, p, q) right = self.lowestCommonAncestor(root.right, p, q) if left and right: return root return left or right
def pathSum(self, root, node, path):
if not root:
return False
path.append(root)
if root == node:
return True
if (root.left and self.pathSum(root.left, node, path)) or (root.right and self.pathSum(root.right, node, path)):
return True
path.pop()
return False
def estimateTransmissions(self, root, p, q):
"""
:type root: TreeNode
:type p: TreeNode
:type q: TreeNode
:rtype: int
"""
lca = self.lowestCommonAncestor(root, p, q)
path1, path2 = [], []
self.pathSum(lca, p, path1)
self.pathSum(lca, q, path2)
path = path1 + path2[::-1]
res = 0
for i in range(1, len(path)):
res += (1 << (i - 1))
return res
原文地址: https://www.cveoy.top/t/topic/b3jU 著作权归作者所有。请勿转载和采集!