一棵树,怎样找到N个节点的公共父节点,最快的方法?

zmzm2008 2006-03-17 11:43:29
一棵树,怎样找到N个节点的公共父节点,最快的方法?
...全文
563 11 打赏 收藏 转发到动态 举报
写回复
用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

70,037

社区成员

发帖
与我相关
我的任务
社区描述
C语言相关问题讨论
社区管理员
  • C语言
  • 花神庙码农
  • 架构师李肯
加入社区
  • 近7日
  • 近30日
  • 至今
社区公告
暂无公告

试试用AI创作助手写篇文章吧