1、 (2)对于任意一棵二叉树,如果其叶结点数为N0,而度数为2的结点(有左右子节点)总数为N2,则N0=N2+1;如上图(左):N0=6,N2=5 右图:N0=8,N2=7 (3)有N个结点的完全二叉树各结点如果用顺序方式表示,则结点之间有如下关系: 如果I1,则其父结点的编号为I/2;如果2*IN,则无左儿子;如果2*I+1N,则无右儿子。(4)具有n个节点的完全二叉树的深度为 log2N+1 4.二叉树的存储结构: (1)顺序存储方式 图5 问题:对于用顺序结构来表示的二叉树A 如何根据节点顺序编号确定所层数和从左数起的编号;反之如何根据层数和从左数起的编号确定节点顺序编号B 如何根据节点顺
2、序编号确定其父节点编号。C 如何根据节点顺序编号确定其左右子节点编号(2)链表存储方式,A 采用数组类型const max= 二叉树的存储容量 TYPE Datetype=节点信息类型 Nodetype=recod Data:datatype; 信息域 Lchild,rchild:integer; 左右指针 End; VAR list:array1.max of nodetype;应用形式: listI.data= listlistI.lchild:=. .左节点 listlistI.rchild:=. .右节点如: 数组下标:12345678 数组D: ABCDEFGH 左指针数组L: 24
3、607000右指针数组R: 35000800B 采用动态数据类型type datatype=. .link=nodetypenodetype=recod data: lchild,rchild:link; end;VAR t: t.data:=. .; t.lchild:=.; 左子节点 t.rchild: 右子节点5.二叉树的遍历运算(递归定义) A B C D E F G H I图6(1) 先序遍历 ABDEGCFHI递归定义访问根;按先序遍历左子树;按先序遍历右子树。 算法如下 动态类型 数组类型type const max= datatype=. . Datetype=link=nod
4、etype Nodetype=recodnodetype=recod Data: L,r: l,r:procedure make(t:link); procedure make(t:intger); begin begin if tnil then if t0 then 访问t.data 访问listt.data make(t.l); make(listt.l); make(t.r); make(listt.r);(2)中序遍历 DBGEACHFI按中序遍历左子树;按中序遍历右子树 make(listt.l)(3)后序遍历 DGEBHIFCA按后序遍历左子树;按后序遍历右子树;访问根练习题1.
5、用顺序存储方式建立一棵深度为N(N0) and (n6); fillchar(e,sizeof(e),0); k:=trunc(exp(n*ln(2)-1; for i:=1 to k do ei:=1;=1 to 26 do bi:=chr(64+i);=1 to 5 do b26+i:=chr(48+i); h: tree(h); writeln;end.【tree2.pas】 program tree2;const人工建立二叉树的链表关系 a:array1.8 of char=(A,BCDEFGH r:array1.8 of integer=(3,5,0,0,0,8,0,0); l:ar
6、ray1.8 of integer=(2,4,6,0,7,0,0,0);array1.7 of integer;procedure search(m: if em=0 then begin write(am); em:=1 if (lm=0) and (rm=0) then exit if lm0 then search(lm); if rm0 then search(rm); search(1);【tree4.pas】仅给出建树过程 procedure crt(var bt:指针记录类型) 按先序边历建树过程 VAR . . BeginRead(ch);If ch=# then bt:=ni
7、lElse New(bt); bt.data:=ch; 建根节点 Crt(bt.l); 建左子树Crt(bt.r); 建右子树6二叉排序树 排序树T是一棵按中序已分类的二叉树,即对于树的每个节点(包括顶点),值比它小的那些节点都在它的左边,值比它大的的右边。按中序遍历,即可得到各个节点的信息域(data)按从小到大顺序的序列。如图是一棵二叉排序树: 73 11 1 5 9 13(1) 下列过程是以tree为根的一棵排序二叉中插入一个信息域值为newdata的节点。Procedure insert(var tree:link;newdata:datatype);Begin If tree=nil
8、 then New(tree); Tree.l:=nil; tree.r: tree.data:=newdata; 插入新节点 End Else If newdatatree.data then Insert(tree.l , newdata); 新节点插在左子树中,以tree.l为子树继续寻找插入位置Else Insert(tree.r , newdata); 新节点插在右子树中,以tree.r为子树继续寻找插入位置 主程序框架如下 var temp: datatype; 节点类型 root : link; 根 begin repeetread(temp); if tempv then fi
9、nd(t.l); else if t.data=w then hyt(d,right) else hyt(d,left);procedure hyt1(p: if leftnil then hyt1(left); write(w:4); if rightnil then hyt1(right); for j:=1 to 8 do hyt(aj,first); hyt1(first); writeln6.普通树转换成二叉树:凡是兄弟就用线连起来,然后去掉父亲到儿子的连线,只留下父母到其第一个子女的连线。 A A B C D B E F G H I E C 普通树 F D G H 转换成二叉树 I 四、例: 1.给出八枚金币a,b,c,d,e,f,g,h,编程以称最少的次数,判定它们蹭是否有假币,如果有,请找出这枚假币,并判定这枚假币是重了还是轻了。
copyright@ 2008-2022 冰豆网网站版权所有
经营许可证编号:鄂ICP备2022015515号-1