二叉树两节点的最低公共树节点

树的编程平时基本没怎么用到,花功夫去专门研究的人不多,所以笔试面试出树的情况比较多,看了别人总结的,自己写一份,加深印象。

参考博客:http://zhedahht.blog.163.com/blog/static/25411174201081263815813/

  二叉树分为有序二叉树(也叫二叉搜索树)和无序二叉树,对于有序二叉树,求节点的最低公共节点,只需要求比其中较小数大、较大数小的节点就可以了,用递归很容易就可以实现。但是对于无序二叉树,再用递归的话会浪费很多时间,会重复遍历,可以用空间换时间,用链表来记录从树节点到所求两个节点的路径,然后求出最后一个公共节点,这个公共节点就是最低公共节点。

#include<iostream>
#include <list>
using namespace std;

typedef struct treeNode
{
int data;
treeNode* lchild;
treeNode* rchild;
}treeNode,*node;


void createTree(node &t)//先序递归建立二叉树(例如输入:2100300)
{
int a;
cin>>a;
if(a==0)
{
t=NULL;
}
else
{
t=new treeNode;
t->data=a;
createTree(t->lchild);
createTree(t->rchild);
}
}

bool getNodeList(int t,node root,list<node> &pathlist)//从需要获取的节点得出路径
{
if(t==root->data)
return true;
pathlist.push_back(root);
bool found=false;
if(root->lchild!=NULL)
found=getNodeList(t,root->lchild,pathlist);
if(!found&&root->rchild!=NULL)
{
found=getNodeList(t,root->rchild,pathlist);
}
if(!found)
pathlist.pop_back();
return found;
}

得出的两个链表是以树节点为开始的两个链表,是一个倒立的"Y"型,只需要从两个链表的节点依次遍历直到不相等即可。
node findLastCommon(list<node> pathlist1,list<node> pathlist2)
{
list<node>::iterator itor1=pathlist1.begin(),itor2=pathlist2.begin();
int length1=0,length2=0;
node plast;
while(itor1!=pathlist1.end()&&itor2!=pathlist2.end())
{
if(*itor1==*itor2)
plast=*itor1;
itor1++;
itor2++;
}

return plast;
}

 


void main()
{
node root;
createTree(root);
cout<<root->data<<endl;
list<node> pathlist1,pathlist2;
getNodeList(6,root,pathlist1);
getNodeList(11,root,pathlist2);
node t=findLastCommon(pathlist1,pathlist2);
cout<<t->data;

 

}

 

posted @ 2016-10-27 15:34  _gardener  阅读(314)  评论(0编辑  收藏  举报