Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

fix 03.03.md --- a bug in LCA algorithm #404

Open
wants to merge 1 commit into
base: master
Choose a base branch
from
Open
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
18 changes: 12 additions & 6 deletions ebook/zh/03.03.md
Original file line number Diff line number Diff line change
Expand Up @@ -29,18 +29,26 @@
* 如果当前结点t 大于结点u、v,说明u、v都在t 的左侧,所以它们的共同祖先必定在t 的左子树中,故从t 的左子树中继续查找;
* 如果当前结点t 小于结点u、v,说明u、v都在t 的右侧,所以它们的共同祖先必定在t 的右子树中,故从t 的右子树中继续查找;
* 如果当前结点t 满足 u <t < v,说明u和v分居在t 的两侧,故当前结点t 即为最近公共祖先;
* 而如果u是v的祖先,那么返回u的父结点,同理,如果v是u的祖先,那么返回v的父结点
* 而如果u是v的祖先,那么返回u,同理,如果v是u的祖先,那么返回v

代码如下所示:

```cpp
//copyright@eriol 2011
//modified by July 2014
public int query(Node t, Node u, Node v) {
public Node query(Node t, Node u, Node v) {
if(u.parent == v) {
return v;
}

if(v.parent == u) {
return u;
}

int left = u.value;
int right = v.value;
Node parent = null;

//二叉查找树内,如果左结点大于右结点,不对,交换
if (left > right) {
int temp = left;
Expand All @@ -58,10 +66,8 @@ public int query(Node t, Node u, Node v) {
} else if (t.value > right) {
parent = t;
t = t.left;
} else if (t.value == left || t.value == right) {
return parent.value;
} else {
return t.value;
return t;
}
}
}
Expand Down