我试图通过自顶向下的递归实现二叉树最小公共祖先(LCA)问题的解决方案。在
我采用的方法是:IDEA: Find the node which has one of the desired nodes in either subtree while the other desired node is the opposite subtree.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
例如:
^{pr2}$
这将返回树的根作为结果。
结果=TreeNode(2)
毫无疑问,根永远是祖先。
然而,存在一个比根-TreeNode(5)更低的共同祖先。在