二叉数实习报告,数据结构.docVIP

  • 8
  • 0
  • 约1.27万字
  • 约 12页
  • 2018-04-01 发布于江西
  • 举报
二叉数实习报告,数据结构

二叉数实习报告 实习题: 编写一个程序,确定二叉树的特征。如:每个节点的层次,从根到该节点的枝长(路径长度),子孙的个数及祖先的个数。每个节点在前序,中序,堠许中访问的序号。 设计: 要存储每个节点的相关信息,采用结构的数组较为合适。因二叉树的节点数可由函数求得, 故采用顺序数组不必担心会浪费空间或空间不足。 存储结构: struct TreeMark { Type data; const BinaryNodeType* Address; int Floor; int Children; int Branch; int Ancestor; int PreorderNumber; int InorderNumber; int PostorderNumber; };//记录节点的所有信息 templateclass Type TreeMarkType* GetTreeMark(BinaryTreeType R) { int N = R.GetRoot()-Size(R.GetRoot()); TreeMarkType* Tree = new TreeMarkType[N]; PostorderType Post(R); Post.First(); int i = 0; while(Post.operator+()) { Tree[i].Address = Post.GetCurrent(); //节点地址 Tree[i].PostorderNumber = i+1; //节点后序中访问序号 Tree[i].data = Post.operator()(); //节点值 Tree[i].Floor = Post.StackSize()+1; //节点层次 Tree[i].Branch = Post.StackSize(); //节点枝长 Tree[i].Ancestor = Post.StackSize(); //节点祖先数 Tree[i].Children = Post.GetCurrent()-Size(Post.GetCurrent())-1; //节点子孙数 i++; Post.operator++(); } PreorderType Pre(R); Pre.First(); int j = 1; while(Pre.operator+())//记录结点在前序遍历的位置 { i = 0; while(Tree[i].Address != Pre.GetCurrent()) i++; Tree[i].PreorderNumber = j; j++; Pre.operator++(); } InorderType In(R); In.First(); j = 1; while(In.operator+())//记录结点在中序遍历的位置 { i = 0; while(Tree[i].Address != In.GetCurrent()) i++; Tree[i].InorderNumber = j; j++; In.operator++(); } for(i=0; iN; i++)//输出节点各信息 { coutdata Tree[i].data Address Tree[i].Addressendl; coutFloors Tree[i].Floor Ancestor Tree[i].Ancestorendl; coutBranch Tree[i].Branch Children Tree[i].Childrenendl; coutPreorderNumber Tree[i].PreorderNumberendl; coutInorderNumberTree[i].InorderNumberPostorderNumber” Tree[i].PostorderNumberendl; coutendl; } return Tree; } 算法思想: 申请一个结构的数组,(大小为二叉树的节点数),对二叉数进行后序遍历, 利用非递归后序遍历的特点,(找到指定节点后,此时在栈中的节点是该节点的所有祖先),算出该节点的层次,祖先数,路径长。以当前节点为根节点,调用 Size()函数, 可计算出该节点的子孙数。然后进行中序和前序遍历,将访问序号记录到对应的节点结构中。 调用关系: 实习任务在函数数TreeMarkType* GetTreeMark(BinaryTreeType R)中全部

文档评论(0)

1亿VIP精品文档

相关文档