【发布时间】:2018-03-09 05:27:14
【问题描述】:
我正在尝试通过自上而下的递归来解决二叉树的最低公共祖先(LCA)问题。
我使用的方法是:
想法:在任一子树中找到具有所需节点之一的节点,而另一个所需节点是相反的子树。
PSEUDOCODE 1. If the value of root is equal to either of the desired node's value, the root is the LCA. 2. Search in the left subtree for either node. 3. Search in the right subtree for either node. 4. If neither of them contains any of the two nodes, the nodes do not exist in the tree rooted at the root node. 5. If each of them contains one node, the root is the LCA. 6. If either one of them contains a node, return it to the root.
这也是 StackOverflow 上 related questions 的答案中推荐的内容。
现在,如果我们假设树的所有节点都具有唯一值,则此代码运行良好。换句话说,这种方法似乎在重复的情况下会失效(或者,它只是我的实现吗?)
我想知道如何修复我的代码以使用重复值。如果这种方法不能产生最佳解决方案,我应该如何改变我的方法?
下面是具体实现:
class TreeNode(object):
def __init__(self, x):
self.val = x
self.left = None
self.right = None
def __repr__(self):
return 'TreeNode({}, {}, {})'.format(self.val, self.left, self.right)
def lowestCommonAncestor(root, p, q):
"""
:type root: TreeNode
:type p: TreeNode
:type q: TreeNode
:rtype: TreeNode
"""
if root is None:
return None
if p.val == root.val or q.val == root.val:
return root
left_subtree = lowestCommonAncestor(root.left, p, q)
right_subtree = lowestCommonAncestor(root.right, p, q)
if left_subtree is None and right_subtree is None:
return None
if left_subtree is not None and right_subtree is not None:
return root
if left_subtree is None:
return right_subtree
else:
return left_subtree
例如:
root = TreeNode(2)
root.left = TreeNode(3)
root.left.left = TreeNode(1)
root.right = TreeNode(5)
root.right.left = TreeNode(7)
root.right.right = TreeNode(1)
print(lowestCommonAncestor(root, TreeNode(1), TreeNode(7)))
这将返回树的根作为结果。 结果 = TreeNode(2)
毫无疑问,根始终是祖先。
但是,存在比根“更低”的共同祖先 - TreeNode(5)。
【问题讨论】:
标签: python algorithm recursion tree