蔡子经数据结构5.9

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60


#include <stdlib.h>
typedef struct ;
struct
{
int val,mark;
node *lchild,*rchild;
};
#define MAXN 100

node* createNodeWithVal(int val)
{
node *rt = (node*)malloc(sizeof(node));
rt->lchild = rt->rchild = NULL;
rt->val = val;
rt->mark = 0;
return rt;
}

4
2 6
1 3 5 7
*/
node* createTree()
{
node *rt = createNodeWithVal(4);
rt->lchild = createNodeWithVal(2);
rt->rchild = createNodeWithVal(6);
rt->lchild->lchild = createNodeWithVal(1);
rt->lchild->rchild = createNodeWithVal(3);
rt->rchild->lchild = createNodeWithVal(5);
rt->rchild->rchild = createNodeWithVal(7);
return rt;
}

//判断两棵树是否一样
int flag = 1;//falg = 1表示俩树一样,否则,俩树不一样
void Judge(node *rt1, node *rt2)
{
if(rt1 == NULL && rt2 == NULL)
return ;
//现在就是俩全都不为空,有一个为空的情况
if((rt1 == NULL && rt2 != NULL) || (rt1 != NULL && rt2 == NULL))//说明一个为空,一个不为空,即树的形态不一样
{
flag = 0;
return ;
}
Judge(rt1->lchild, rt2->lchild);
Judge(rt1->rchild, rt2->rchild);
}

int main()
{
node *rt1 = createTree();
node *rt2 = createTree();
rt2->rchild->rchild->rchild = createNodeWithVal(10);
Judge(rt1, rt2);
printf("%dn",flag);
}