主要是遍历,二叉搜索树的基础。

 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
#pragma once

#include <stdio.h>
#include <stdlib.h>

typedef int type;

struct BinaryTreeNode {
    type data;
    struct BinaryTreeNode *left;
    struct BinaryTreeNode *right;
};

/**
 * 先序遍历, 根->左->右
 */
void preorder(struct BinaryTreeNode *node) {
    if (node != NULL) {
        printf("%d ", node->data);
        preorder(node->left);
        preorder(node->right);
    }
}

/**
 * 中序遍历, 左->根->右
 */
void inorder(struct BinaryTreeNode *node) {
    if (node != NULL) {
        inorder(node->left);
        printf("%d ", node->data);
        inorder(node->right);
    }
}

/**
 * 后序遍历, 左->右->根
 */
void postorder(struct BinaryTreeNode *node) {
    if (node != NULL) {
        postorder(node->left);
        postorder(node->right);
        printf("%d ", node->data);
    }
}

struct BinaryTreeNode* BinaryNodeBuild(type data) {
    struct BinaryTreeNode *node = (struct BinaryTreeNode*)malloc(sizeof(struct BinaryTreeNode));
    node->data = data;
    node->left = NULL;
    node->right = NULL;
    return node;
}

void test() {
    struct BinaryTreeNode *node1, *node2, *node3, *node4;
    node1 = BinaryNodeBuild(4);
    node2 = BinaryNodeBuild(5);
    node3 = BinaryNodeBuild(6);
    node4 = BinaryNodeBuild(7);

    node1->left = node2;
    node1->right = node3;
    node2->right = node4;

    preorder(node1);
    printf("\n");
    inorder(node1);
    printf("\n");
    postorder(node1);
    printf("\n");
}