社区
C语言
帖子详情
一棵树,怎样找到N个节点的公共父节点,最快的方法?
zmzm2008
2006-03-17 11:43:29
一棵树,怎样找到N个节点的公共父节点,最快的方法?
...全文
563
11
打赏
收藏
一棵树,怎样找到N个节点的公共父节点,最快的方法?
一棵树,怎样找到N个节点的公共父节点,最快的方法?
复制链接
扫一扫
分享
转发到动态
举报
写回复
配置赞助广告
用AI写文章
11 条
回复
切换为时间正序
请发表友善的回复…
发表回复
打赏红包
digifish
2006-03-18
打赏
举报
回复
在网上查找“最近公共祖先”或者LCA (Lowest Common Ancestor)算法.
dzy1982
2006-03-17
打赏
举报
回复
树没有公共节点。。。。。。
-------------------
所有的子节点都有公共的父节点。
danjiewu
2006-03-17
打赏
举报
回复
看错,公共父节点。。。。。
深度优先遍历,N个节点值为1,其他节点值为0。
int count(){
if是叶子 return value;
else return value + child1.count() + ... +childn.count();
}
count值等于N的就是公共父节点。
owen_myw
2006-03-17
打赏
举报
回复
说明树是什么特殊的树
danjiewu
2006-03-17
打赏
举报
回复
树没有公共节点。。。。。。
lz那个是叫图了吧?
jinjiajie
2006-03-17
打赏
举报
回复
我觉得是全部往回找,一步步来.......是什么树?有规律的树吗?
du51
2006-03-17
打赏
举报
回复
这是我很早以前写的.很笨不要笑...二叉树.
#include<iostream>
using namespace std;
struct Node{ //结点
int data;
Node *lchild;
Node *rchild;
};
Node *createNode(int data) //建结点
{
Node *node=new Node;
node->data=data;
node->lchild=0;
node->rchild=0;
return node;
}
Node *buildTree() //建树
{
Node *root=0;
return root;
}
void insertTree(Node *&root,int data) //插成有序树
{
Node *node=createNode(data);
if(!root)root=node;
else if(node->data<root->data)insertTree(root->lchild,node->data);
else insertTree(root->rchild,node->data);
return ;
}
void printTree(Node *root) //升序打印
{
if(!root)return ;
printTree(root->lchild);
cout<<root->data<<" ";
printTree(root->rchild);
}
int finder(Node *root,int data)
{
if(!root)return 0;
if(root->data==data)return 1;
else return (finder(root->lchild,data)||finder(root->rchild,data));
}
void findfather(Node *root,int i,int j)
{
if(!root)return;
if(finder(root,i)&&finder(root,j))
{
if(finder(root->lchild,i)&&finder(root->lchild,j))findfather(root->lchild,i,j);
else if(finder(root->rchild,i)&&finder(root->rchild,j))findfather(root->rchild,i,j);
else cout<<"它们的是近父结点为:"<<root->data<<endl;
}
else cout<<"有结点不在树中"<<endl;
}
int main(int argc,char *argv[])
{
int data,i,j;
Node *root=buildTree();
cout<<"请输入你的数据以-1结束"<<endl;
cin>>data;
while(data!=-1)
{
insertTree(root,data);
cin>>data;
}
printTree(root);
cout<<endl;
cout<<"请输入你要寻找的两个数据"<<endl;
cin>>i>>j;
findfather(root,i,j);
system("PAUSE");
return 0;
}
dzy1982
2006-03-17
打赏
举报
回复
楼主的意思估计是第一个公共父节点。
zhumeicao
2006-03-17
打赏
举报
回复
题目很含糊哦
firetoucher
2006-03-17
打赏
举报
回复
有点疑问
1 题目中所谓的“父节点”,是什么意思?包括祖父节点么?换句话说,题目的意思是否是指找包含N个节点的最小树的根节点?
2 节点有父指针么?
FT
--
Anything one man can imagine, other men can make real.
zmzm2008
2006-03-17
打赏
举报
回复
up
二叉树的最近
公共
祖先II1
百度百科中最近
公共
祖先的定义为:“对于有根树 T 的两个
节点
p、q,最近
公共
祖先表示为一个
节点
x,满足 x 是 p、q 的祖先且 x 的深度尽可能大(一个节
九度OJ-题目1509:树中两个结点的最低
公共
祖先的测试数据
这是九度OJ-题目1509:树中两个结点的最低
公共
祖先的测试数据,input.txt是输入数据,output.txt是输出数据。
第3章 第1-2节 树及二叉树(C++版).ppt
第3章 第1-2节 树及二叉树(C++版).ppt
树和森林作业答案.zip
树和森林作业答案.zip
高级数据结构-----刘汝佳
平衡二叉树 可并优先队列 线段树和树状数组基础 RMQ与LCA
C语言
70,037
社区成员
243,243
社区内容
发帖
与我相关
我的任务
C语言
C语言相关问题讨论
复制链接
扫一扫
分享
社区描述
C语言相关问题讨论
社区管理员
加入社区
获取链接或二维码
近7日
近30日
至今
加载中
查看更多榜单
社区公告
暂无公告
试试用AI创作助手写篇文章吧
+ 用AI写文章