⭐ 欢迎来到虫虫下载站! | 📦 资源下载 📁 资源专辑 ℹ️ 关于我们
⭐ 虫虫下载站

📄 creattree.cpp

📁 通过GOTO LOOP语句创建一颗二叉树
💻 CPP
字号:
#include <iostream>
#include <string>
using namespace std;

struct node 
{
	int data;
	struct node *lchild,*rchild;
};//定义结点信息

node  *CreatTree()
{	
	struct node *head=NULL;
	struct node *newhead=NULL;
	int *p=NULL;
	int i=0;
	int n=0;
	cout<<"please input how many son do you want to creat:";
	cin>>n;
	p=new int[n];
loop_1:
	{
		if (i==n)
		{
			goto loop_over;
		}
		struct node *newnode;
		newnode=new node;
		cout<<"please input data to node:";
		cin>>newnode->data;
		newnode->lchild=NULL;
		newnode->rchild=NULL;
		if (newnode->data==10000)//如果输入的结果为10000,则退出树的创建。
		{						
			goto loop_over;
		}
		if (head==NULL)
		{
			head=newnode;
			newhead=head;
			p[i]=head->data;
			i++;//入栈
			goto loop_1;
		}
		while (newnode->data==0)
		{
		
			i--;
			if (i==-1)
			{	
				goto loop_over;
			}
			newhead->data=p[i];//出栈
			cout<<"please input data to node:";
			cin>>newnode->data;
			if (newnode->data!=0)
			{
				newhead->rchild=newnode;
				p[i]=newnode->data;
				i++;//入栈
				newhead=newnode;
				goto loop_1;
			}
			
		}
		newhead->lchild=newnode;
		p[i]=newnode->data;
		i++;//入栈
		newhead=newnode;
		goto loop_1;
	}
loop_over:
	delete [] p;
	return head;
	
}

void display(struct node *head)
{
	if (head!=NULL)
	{
		display(head->lchild);
		cout<<head->data;
		display(head->rchild);
	}

}

void main()
{
	struct node *trees;
	trees=CreatTree();
	display(trees);
}

⌨️ 快捷键说明

复制代码 Ctrl + C
搜索代码 Ctrl + F
全屏模式 F11
切换主题 Ctrl + Shift + D
显示快捷键 ?
增大字号 Ctrl + =
减小字号 Ctrl + -