tree2

전전컴/C++ 2013. 10. 28. 23:46





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
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
#include <iostream>
#include <string>
using namespace std;
 
typedef struct tTreeNode{
    struct tTreeNode *left, *right;
    char data;
}TreeNode;
 
TreeNode* createNode(TreeNode* left, char root, TreeNode* right){
    TreeNode *p = (TreeNode*)malloc(sizeof(TreeNode));
    
    p->left = left;
    p->right = right;
    p->data = root;
 
    return p;
}
 
void destroyTree(TreeNode* p){
    if( p == NULL) return;
 
    destroyTree(p->left);
    destroyTree(p->right);
    cout<<"node remove"<<endl;
    free(p);
}
 
void preorder(TreeNode* root){
    if(root == NULL) return;
 
    cout<<root->data;
    preorder(root->left);
    preorder(root->right);
}
 
void postorder(TreeNode* root){
    if(root == NULL) return;
    
    postorder(root->left);
    postorder(root->right);
    cout<<root->data;
}
 
void inorder(TreeNode* root){
    if(root == NULL ) return;
 
    inorder(root->left);
    cout<<root->data;
    inorder(root->right);
 
}
 
void main(){
    TreeNode* a = createNode(NULL, 'a', NULL);
    TreeNode* b = createNode(NULL, 'b', NULL);
    TreeNode* c = createNode(NULL, 'c', NULL);
    TreeNode* d = createNode(NULL, 'd', NULL);
 
    TreeNode* plus1 = createNode(b, '+', c);
    TreeNode* multi = createNode(a, '*', plus1);
    TreeNode* plus2= createNode(multi, '+', d);
    
    cout<<"Preorder========"<<endl;
    preorder(plus2);
    cout<<endl;
    cout<<"Postorder======="<<endl;
    postorder(plus2);
    cout<<endl;
    cout<<"Inorder========="<<endl;
    inorder(plus2);
    cout<<endl;
 
 
    destroyTree(plus2);
 
}


설정

트랙백

댓글