在二进制搜索树中查找最低公祖的C ++程序
具有最多两个子代的二叉树,分别指定为左子代和右子代。这是一个C++程序,用于在二叉树中找到最低的公共祖先。
算法
Begin Create a structure n to declare data d, a left child pointer l and a right child pointer r.
Create a function to create newnode. Call a function LCA() to Find lowest common ancestor in a binary tree:
Assume node n1 and n2 present in the tree.
If root is null, then return.
If root is not null there are two cases.
a) If both n1 and n2 are smaller than root, then LCA lies in left.
b) If both n1 and n2 are greater than root, then LCA lies in right.
End.范例程式码
#include<iostream>
using namespace std;
struct n {
int d;
struct n* l, *r;
}*p = NULL;
struct n* newnode(int d) {
p = new n;
p->d= d;
p->l = p->r = NULL;
return(p);
}
struct n *LCA(struct n* root, int n1, int n2) {
if (root == NULL)
return NULL;
if (root->d > n1 && root->d > n2)
return LCA(root->l, n1, n2);
if (root->d< n1 && root->d < n2)
return LCA(root->r, n1, n2);
return root;
}
int main() {
n* root = newnode(9);
root->l = newnode(7);
root->r = newnode(10);
root->l->l = newnode(6);
root->r->l= newnode(8);
root->r->r = newnode(19);
root->r->l->r = newnode(4);
root->r->r->r = newnode(20);
int n1 = 20, n2 = 4;
struct n *t = LCA(root, n1, n2);
cout<<"最低共同祖先20和4是:" <<t->d<<endl;
n1 = 7, n2 = 6;
t = LCA(root, n1, n2);
cout<<"最低共同祖先7和6是:" << t->d<<endl;
}输出结果
最低共同祖先20和4是:9 最低共同祖先7和6是:7
热门推荐
1 训练狗狗基础
2 怎么训练狗狗笑
3 怎么训练狗狗卧下
4 上海狗狗训练基地
5 训练狗狗排便
6 狗狗基础训练
8 如何训练狗狗装死
9 狗狗站姿训练
10 狗狗训练用品
11 训练狗狗吧
12 狗狗要怎么训练
13 怎么训练狗狗玩球
14 训练狗狗唤回
15 狗狗训练躺下
16 狗狗训练指令
17 狗狗的训练技巧
18 狗狗不好训练