#include <iostream>
#include <stack>
using namespace std;
struct BinaryTreeNode{
char t_value;
BinaryTreeNode *t_left;
BinaryTreeNode *t_right;
};
void createtree(BinaryTreeNode* &T){
char val;
cin>>val;
if(val=='#'){
T = NULL;
}else{
T = new BinaryTreeNode();
if(T==NULL) return ;
T->t_value = val;
createtree(T->t_left);
createtree(T->t_right);
}
}
void proorder(BinaryTreeNode *T){
if(T==NULL) return ;
cout<<T->t_value;
proorder(T->t_left);
proorder(T->t_right);
}
//先序非递归
void proorder2(BinaryTreeNode *T){
if(T==NULL) return ;
stack<BinaryTreeNode *> s;
BinaryTreeNode *p = T;
while(!s.empty()||p!=NULL){
while(p!=NULL){
cout<<p->t_value;
s.push(p);
p=p->t_left;
}
if(!s.empty()){
p = s.top();
s.pop();
p = p->t_right;
}
}
}
//找树的子结构,从T1中找T2的结构
bool findchildstruct(BinaryTreeNode *T1,BinaryTreeNode *T2){
bool result = false;
if(T1!=NULL&&T2!=NULL){
if(T1->t_value == T2->t_value)
result = DoesTreehaveTree(T1,T2);
if(!result)
result = findchildstruct(T1->t_left,T2);
if(!result)
result = findchildstruct(T1->t_right,T2);
}
return result;
}
bool DoesTreehaveTree(BinaryTreeNode *T1,BinaryTreeNode *T2){
if(T1 == NULL) return true;
if(T2 == NULL) return true;
if(T1->t_value!=T2->t_value) return false;
return DoesTreehaveTree(T1->t_left,T2->t_left)&&DoesTreehaveTree(T1->t_right,T2->t_right);
}
int main(){
BinaryTreeNode *t1 = NULL;
cout<<"\n按先序序列输入结点序列,'#'代表空"<<endl;
createtree(t1);
cout<<"\n按先序递归序列遍历结果为"<<endl;
proorder(t1);
cout<<"\n按先序非递归序列遍历结果为"<<endl;
proorder2(t1);
cout<<"\n按先序序列输入结点序列,'#'代表空"<<endl;
BinaryTreeNode *t2 = NULL;
createtree(t2);
return 0;
}
树的子结构
最新推荐文章于 2022-04-20 20:23:54 发布