0025二叉树的设计与实现

本文介绍了如何使用递归算法按先根次序遍历二叉树。算法包括三个步骤:访问根节点,递归遍历左子树,递归遍历右子树。首先定义二叉树节点类,然后通过递归实现遍历过程。
摘要由CSDN通过智能技术生成

按先根次序遍历二叉树,利用递归算法。算法基本描述:

1)二叉树为空,返回;否则继续;

2)从根节点开始,访问当前节点;

3)按先根次序遍历当前节点左子树;

3)按先根次序遍历当前节点右子树;

先定义二叉树节点类:

#ifndef TreeNode1_H_
#define TreeNode1_H_
#include <iostream>
using namespace  std;

class TreeNode1
{
public:
	char data;
	TreeNode1 *left,*right;
	TreeNode1(char ch='?');
	~TreeNode1(){}
	void preorderChild(TreeNode1 *p);
	void inorderChild(TreeNode1 *p);
	void postorderChild(TreeNode1 *p);
};

TreeNode1::TreeNode1(char ch)
{
	data = ch;
	left = NULL;
	right = NULL;
}
//preorder 
void TreeNode1::preorderChild(TreeNode1 *p)
{
	if (p!=NULL)
	{
		cout<<p->data<<" ";
		preorderChild(p->left);
		preorderChild(p->right);
	}
}
//inorder
void TreeNode1::inorderChild(TreeNode1 *p)
{
	if (p!=NULL)
	{
		inorderChild(p->left);
		cout<<p->data<<" ";
		inorderChild(p->right);
	}
}
//postorder
void TreeNode1::postorderChild(TreeNode1 *p)
{
	if (p!=NULL)
	{
		postorderChild(p->left);
		postorderChild(p->right);
		cout<<p->data<<" ";
	}
}

#endif//TreeNode1_H_
再定义二叉树类:

#ifndef Tree1_H_
#define Tree1_H_
#include "TreeNode1.h"
#include <iostream>
using namespace std;

class Tree1
{
public:
	TreeNode1 *root;
	Tree1(char *str="");
	~Tree1();
	TreeNode1* create(char *str);
	void destroy(TreeNode1 *p);//destroy binary tree
	void preorder();
	void inorder();
	void postorder();
};
void Tree1::preorder()
{
	cout<<"先序遍历二叉树:";
	root->preorderChild(root);
	cout<<endl;
}
void Tree1::inorder()
{
	cout<<"中序遍历二叉树:";
	root->inorderChild(root);
	cout<<endl;
}
void Tree1::postorder()
{
	cout<<"后序遍历二叉树:";
	root->postorderChild(root);
	cout<<endl;
}

//以标明空子树的先序次序遍历建立二叉树
Tree1::Tree1(char *str)
{
	root=NULL;
	if (str!="")
	{
		cout<<"创建二叉树:"<<endl;
		root=create(str);
		cout<<endl;
	}
}
TreeNode1 *Tree1::create(char *str)
{
	TreeNode1 *p=NULL;
	static int i=0;
	cout<<"调用"<<str[i]<<endl;
	if(str[i]!='.')//空子树标记一个点
	{
		p=new TreeNode1(str[i]);
		i++;
		p->left=create(str);
		p->right=create(str);
	}
	else
		i++;
	if(p==NULL)
		cout<<"返回NULL"<<endl;
	else
		cout<<"返回"<<p->data<<endl;
	return p;
}

//撤销二叉树
Tree1::~Tree1()
{
	cout<<"撤销二叉树:";
	destroy(root);
	root=NULL;
	cout<<endl;
}

void Tree1::destroy(TreeNode1 *p)
{
	if(p!=NULL)
	{
		destroy(p->left);
		destroy(p->right);
		cout<<p->data<<" ";
		delete p;
	}
}

#endif//Tree_H_


在主函数文件中检测:


#include "Tree1.h"

void main(void)
{
	char *str="ABD.G...CE..FH...";
	cout<<"the Tree: "<<str<<endl;
	Tree1 t(str);
	t.preorder();
	t.inorder();
	t.postorder();
	
}

结果:




评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值