二叉树输入问题
#include<iostream>
using namespace std;
template <class T>
struct BinTreeNode //二叉树结点类定义
{T data; //数据域
BinTreeNode<T> *leftChild, *rightChild; //左子女、右子女链域
};
template <class T>
class BinaryTree //二叉树类定义
{
public:
BinaryTree (BinTreeNode<T> *&root); //构造函数
void Print_PreOrder(BinTreeNode<T> *&root);
void Creat(BinTreeNode<T> *&root);//从文件读入建树
void Print_InOrder(BinTreeNode<T> *&root);
protected:
BinTreeNode<T> *root; //二叉树的根指针
};
template <class T>
BinaryTree<T>::BinaryTree (BinTreeNode<T> *&root)
{Creat(root); }
template <class T>
void BinaryTree<T>::Creat(BinTreeNode<T> *&root)
{char ch; cin>>ch;
if(ch=='#') root=NULL;
else
{root = new BinTreeNode<T>; //建立根结点
root->data=ch;
Creat(root->leftChild); //递归建立左子树
Creat(root->rightChild);//递归建立右子树
}
}
template <class T>
void BinaryTree<T>::Print_PreOrder(BinTreeNode<T> *&root)
{if(root==NULL) return ;
else{cout<<root->data<<" ";
Print_PreOrder(root->leftChild); Print_PreOrder(root->rightChild);
}}
template <class T>
void BinaryTree<T>::Print_InOrder(BinTreeNode<T> *&root)
{if(root==NULL) return ;
else
{Print_PreOrder(root->leftChild);
cout<<root->data<<" ";
Print_PreOrder(root->rightChild);
}}
void main()
{ int count=0;
cout<<"请输入节点元素,以#结束!"<<endl;
BinTreeNode<char> *bt;
bt=new BinTreeNode<char>;
BinaryTree<char> b(bt);
cout<<"树的前序访问遍序为:"<<endl;
b.Print_PreOrder(bt);cout<<endl;
cout<<"树的中序访问遍序为:"<<endl;
b.Print_InOrder(bt);cout<<endl;
system("pause");
}
这种二叉树输入的规则到底是怎么样???
比如我输入abcdefg########
这样到底是一棵怎么样的二叉树呢????
[解决办法]
template <class T>
BinaryTree<T>::BinaryTree (BinTreeNode<T> *&root)
{ Creat(root); }
template <class T>
void BinaryTree<T>::Creat(BinTreeNode<T> *&root)
{ char ch; cin>>ch;
if(ch=='#') root=NULL;
else
{root = new BinTreeNode<T>; //建立根结点
root->data=ch;
Creat(root->leftChild); //递归建立左子树
Creat(root->rightChild);//递归建立右子树
}
}
例如输入: a b c # # # d # #
a
b d
c # # #
# #