关于二叉树的生成, 遍历 在线求指导!该如何处理
关于二叉树的生成, 遍历 在线求指导!
为什么下面的程序运行时, 进行遍历操作, 会出现指针越界呢?
我还以为二叉树的应用很简单, 但是, 因为这个遍历, 我已经烦恼了2个小时了...
------解决方案--------------------
create只返回NULL值,那么create函数中
为什么下面的程序运行时, 进行遍历操作, 会出现指针越界呢?
我还以为二叉树的应用很简单, 但是, 因为这个遍历, 我已经烦恼了2个小时了...
- C/C++ code
#include <iostream> using namespace std; const int queueSize = 100; //层序遍历所用的队列的最大度 struct biNode //用结构体定义二叉树 { char word; biNode *lchild, *rchild; }; biNode *creat(biNode *node) //生成二叉树 { cout<<"请输入节点\n (输入数字 0 , 即结束节点输入\n"; char word; cin>>word; if (word == '0') return NULL; //结束子树 else { node = new biNode; node->word = word; node->lchild = creat(node); node->rchild = creat(node); } } biNode *setup(biNode *root) { biNode *go; //执行节点 go = new biNode; cout<<"请输入根节点\n "; cin>>go->word; root = go; creat(go); //递归生成二叉树 return root; } void preOrder(biNode *root) //前序遍历 { if (root != NULL) { cout<<root->word<<" "; preOrder(root->lchild); preOrder(root->rchild); } } void inOrder(biNode *root) //中序遍历 { if (root != NULL) { inOrder(root->lchild); cout<<root->word<<" "; inOrder(root->rchild); } } void postOrder(biNode *root) //后续遍历 { if (root != NULL) { postOrder(root->lchild); postOrder(root->rchild); cout<<root->word<<" "; } } void levelOrder(biNode *root) //层序遍历 { biNode *queue[queueSize]; biNode *q; int front, rear; front = rear = -1; if (root == NULL) return ; queue[++rear] = root; while (front != rear) { q = queue[++front]; cout<<q->word; if (q->lchild != NULL) queue[++rear] = q->lchild; if (q->rchild != NULL) queue[++rear] = q->rchild; } } int main() { biNode *root, *go; root = go = NULL; //初始化 while(1) { cout<<"\t\t二叉树, 二叉树, 二叉树!\n\n"; cout<<"1, 生成二叉树\n"; cout<<"2, 前序遍历\n"; cout<<"3, 中序遍历\n"; cout<<"4, 后续遍历\n"; cout<<"5, 程序遍历\n"; cout<<"6, 退出\n"; cout<<"输入 1 到 6 的数字, 选择相应功能\n"; int judge; cin>>judge; switch (judge) { case 1: { root = setup(go); break; } case 2: { cout<<"前序遍历:\n"; preOrder(root); break; } case 3: { cout<<"中序遍历:\n"; inOrder(root); break; } case 4: { cout<<"后续遍历:\n"; postOrder(root); break; } case 5: { cout<<"层序遍历:\n"; levelOrder(root); break; } case 6: { exit(1); } default: { cout<<"Please enter a number from 1 to 6!\n"; break; } } } return 0; }
------解决方案--------------------
create只返回NULL值,那么create函数中
- C/C++ code
node->lchild = creat(node); node->rchild = creat(node);