标签:
二叉搜索树3.深入理解二叉树的三种遍历方式,程序中采用了最简单的中序遍历,包括二叉树的递归遍历和非递归遍历;
#include<iostream> #include<cstdio> #include<cstring> #include<cstdlib> using namespace std; typedef struct node { node *left,*right; int value; }*N; node *tree1,*tree2; int n; char s1[11],s2[11]; void insert_node(node *tree,int t) { if(t<tree->value){ if(tree->left==0){ node *n1; n1=(node *)malloc(sizeof(node )); n1->left=n1->right=0; n1->value=t; tree->left=n1; tree=n1; } else insert_node(tree->left,t); } else{ if(tree->right==0){ node *n1; n1=(node *)malloc(sizeof(node )); n1->left=n1->right=0; n1->value=t; tree->right=n1; tree=n1; } else insert_node(tree->right,t); } } void create_binarytree(node *tree,char s[]) { int l=strlen(s),t,k=0; for(int i=1;i<l;i++) { t=s[i]-'0'; insert_node(tree,t); } } int sum; void search_binary(node *n1,int s[]) { s[sum]=n1->value; if(n1->left) { sum++;search_binary(n1->left,s);} if(n1->right) { sum++;search_binary(n1->right,s);} } int main() { memset(s1,0,sizeof(s1)); memset(s2,0,sizeof(s2)); int s3[13],s4[13]; while(1){ scanf("%d",&n); if(n==0) break; memset(s3,0,sizeof(s3)); scanf("%s",s1); tree1=(node *)malloc(sizeof(node )); tree1->value=s1[0]-'0'; tree1->left=tree1->right=0; create_binarytree(tree1,s1); sum=0; search_binary(tree1,s3); for(int i=1;i<=n;i++) { memset(s4,0,sizeof(s4)); memset(s2,0,sizeof(s2)); scanf("%s",s2); tree2=(node *)malloc(sizeof(node )); tree2->value=s2[0]-'0';tree2->right=tree2->left=0; create_binarytree(tree2,s2); sum=0; search_binary(tree2,s4); bool flag=1; for(int j=0;j<10;j++) { if(s3[j]!=s4[j]) flag=0; } if(flag) printf("YES\n"); else printf("NO\n"); } } return 0; }
标签:
原文地址:http://blog.csdn.net/yuanchang_best/article/details/42980917