二叉树及二叉树的操作

上传人:工**** 文档编号:487057900 上传时间:2022-10-16 格式:DOCX 页数:4 大小:10.24KB
返回 下载 相关 举报
二叉树及二叉树的操作_第1页
第1页 / 共4页
二叉树及二叉树的操作_第2页
第2页 / 共4页
二叉树及二叉树的操作_第3页
第3页 / 共4页
二叉树及二叉树的操作_第4页
第4页 / 共4页
亲,该文档总共4页,全部预览完了,如果喜欢就下载吧!
资源描述

《二叉树及二叉树的操作》由会员分享,可在线阅读,更多相关《二叉树及二叉树的操作(4页珍藏版)》请在金锄头文库上搜索。

1、二叉树及二叉树的操作#includeusing namespace std;templateclass BTNodepublic:BTNode() lchild = rchild = NULL;BTNode(const T& X)element = x;lchild = rchild = NULL;BTNode(const T& x,BTNode *l,BTNode *r)element = x;lchild = l;rchild = r;T element;BTNode *lchild,*rchild;templateclass BinaryTreepublic:BinaryTree()ro

2、ot = NULL;BinaryTree();bool IsEmpty() const;void Clear();bool Root(T& x) const;void MakeTree(const T& x,BinaryTree& left,BinaryTree& right);void BreakTree(T& x,BinaryTree& left,BinaryTree& right);void PreOrder(void (*Visit)(T& x)先序遍历void LevelOrder(void (*Visit)(T& x)后续遍历void HierarchyBiTree(BiTree

3、Root)层次遍历protected:BTNode *root;private:void Clear(BTNode *t);void PreOrder(void (*Visit)(T& x),BTNode *t);void LevelOrder(void (*Visit)(T& x),BTNode *t);;templateBinaryTree:BinaryTree()Clear();templatebool IsEmpty()if(!root)return true;elsereturn false;templatevoid BinaryTree:Clear()if(root)delete

4、root;PreOrder(Visit,root-lchild);PreOrder(Visit,root-rchild);root = NULL;templatebool BinaryTree:Root(T& x) const if(root)x = root-element;elsereturn false;templatevoid BinaryTree:MakeTree(const T& x,BinaryTree& left,BinaryTree& right) if(root|&left=&right)return;root = new BTNode(x,left.root,right.

5、root);left.root = right.root = NULL;templatevoid BinaryTree:BreakTree(T& x,BinaryTree& left,BinaryTree& right)if(!root|&left=&right|left.root|right.root)return;x = root-element;left.root = root-lchild;right.root = root-rchild;delete root;root = NULL;templatevoid BinaryTree:PreOrder(void (*Visit)(T&

6、x)PreOrder(Visit,root);templatevoid BinaryTree:PreOrder(void (*Visit)(T& x),BTNode *t)if(t)Visit(t-element);PreOrder(Visit,t-lchild);PreOrder(Visit,t-rchild);void Visit(char& x);int main()BinaryTree a,b,x,y,z; char e=A;y.MakeTree(E,a,b);z.MakeTree(F,a,b);x. MakeTree(C,y,z);y.MakeTree(D,a,b);z.MakeTr

7、ee(B,y,x);z.PreOrder(Visit);z.BreakTree(e,y,x);x. PreOrder(Visit);y.PreOrder(Visit);return 0;templatevoid HierarchyBiTree(BiTree Root)LinkQueue *Q; /保存当前节点的左右孩子的队列if (Root = NULL) return ; /树为空则返回BiNode *p = Root;临时保存树根Root到指针p中Visit(p-data); / 访问根节点if (p-lchild) EnQueue(Q, p-lchild); / 若存在左孩子,左孩子进队列if (p-rchild)EnQueue(Q, p-rchild); / 若存在右孩子,右孩子进队列while (!QueueEmpty(Q) DeQueue(Q, p); / 出队列Visit(p-data);/访问当前节点if (p-lchild) if (p-rchild) EnQueue(Q, p-lchild); /若存在左孩子,左孩子进队列EnQueue(Q, p-rchild); /若存在右孩子,右孩子进队列

展开阅读全文
相关资源
正为您匹配相似的精品文档
相关搜索

最新文档


当前位置:首页 > 学术论文 > 其它学术论文

电脑版 |金锄头文库版权所有
经营许可证:蜀ICP备13022795号 | 川公网安备 51140202000112号