首页 > 编程知识 正文

二叉树节点最大距离,二叉树两节点最大路径

时间:2023-05-04 13:25:40 阅读:160332 作者:2846

假设二叉树用二叉树的存储结构:

1 .“找到从根节点到叶节点的路径”包括两种不同的算法:基于栈辅助后序非递归遍历的算法和基于队列辅助层次遍历的算法

2 .对于某一给定节点,求其所有祖先:递归求解。

具体的实现代码如下

/* author : ibsendate :2015.12.15 */# includeiostreamusingnamespacestd; const int M=1000; typedef struct node{char data; struct node *lc,*rc; }BTree; voidcreat_btree(btree*h,char *str ) /括号二叉树BTree *st[M],*p; int pos=0,k,top=-1; char ch=str[0]; h=NULL; 威尔(ch!=' ' ) {switch(ch ) (case ) ) :ST[top]=p; k=1; 黑; case ' ) ' :top--; 黑; case ',' :k=2; 黑; default :p=new BTree (; p-data=ch; p-lc=p-rc=NULL; if(h==null ) h=p; ELSE{if(k==1) st[top]-lc=p; else st[top]-rc=p; }}ch=str[ pos]; }voidall_path(btree*h ) /从根节点到叶节点的路径BTree *st[M],*p; int top=-1; if(h!=null(do ) while ) h!=null}{ST[top]=h; h=h-lc; (}p=NULL; bool flag=1; wile(flagtop-1 ) {h=st[top]; if(h-RC==p ) if ) h-LC==nullh-RC==null ) for ) intI=0; itop; I ) coutst[i]-data'-- '; coutst[top]-dataendl; }top----; p=h; (else ) h=h-RC; flag=0; }}while(top-1 ); coutendl; }voidall_path1(btree*h ) /从根节点到叶节点的反向路径structsnode ) btree*node; int par; ) }que[M]; int head=-1,tail=-1; BTree *q; if(h!=null}{que[tail].node=h; que[tail].par=-1; 头儿!=tail}{q=que[head].node; if(q-LC==nullq-RC==null ) ) for ) intI=head; que[i].par!=-1; I=que [ I ].par ] cout que [ I ].node-data '-- '; coutque[0].node-dataendl; (if ) q-LC!=null}{que[tail].node=q-LC; que[tail].par=head; (if )问答!=null}{que[tail].node=q-RC; que[tail].par=head; }}}boolancestor(btree*h,char x ) if ) h==null ) return false; ELSEif () ) h-LC!=nullh-LC-data==x(|(h-RC!=NULLh-rc-data==x ) ({couth-data ' '; 返回真; }elseif(ancestor(h-LC,x )|ancestor (h-RC,x ) ) {couth-data ' ); 返回真; }else return false; }char str[M]; int main () {BTree *h; wile(cinstr ) creat_btree,str ); all_path(h; all_path1(h; cout '输出值为x的节点的所有祖先:'endl; char x; wile(cinx ) if (! ancestor(h,x ) ) cout'false! ' endl; cout'*******'endl; }return 0; () ) ) ) )。

版权声明:该文观点仅代表作者本人。处理文章:请发送邮件至 三1五14八八95#扣扣.com 举报,一经查实,本站将立刻删除。