树如何找共同祖先_寻找最小共同祖先在二叉树

I have a binary tree as below. I need to find the least common ancestor (LCA). e.g LCA of 6 and 4 is 1, LCA of 4 and 5 is 2.

1

/ \

2 3

/ \ / \

4 5 6 7

Can anyone please suggest how should I approach and solve this problem?

解决方案

Start with an ordinary depth-first search algorithm:

public Node find(Node node, int target) {

if(node == null || node.value == target) {

return node;

}

if(node.value > target) {

return find(node.left, target);

} else {

return find(node.right, target);

}

}

Now, adapt this to take two "target" parameters, target1 and target2.

When the search for target1 takes you left, and the search for target2 takes you right, you've found the LCA.

This assumes that both targets actually do exist. If you need to assert that they do, you'll need to continue the search after finding the potential LCA.

public Node findLca(Node node, int t1, int t2) {

if(node == null) {

return null;

}

if(node.value > t2 && node.value > t1) {

// both targets are left

return findLca(node.left, t1, t2);

} else if (node.value < t2 && node.value < t1) {

// both targets are right

return findLca(node.right, t1, t2);

} else {

// either we are diverging or both targets are equal

// in both cases so we've found the LCA

// check for actual existence of targets here, if you like

return node;

}

}

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值