按先根次序遍历二叉树,利用递归算法。算法基本描述:
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();
}
结果: