二叉树最小公共祖先Java,递归二叉树的最小公共祖先

我试图通过自顶向下的递归实现二叉树最小公共祖先(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)更低的共同祖先。在

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值