數據結構學習筆記之二叉樹 BST

 BST是二叉樹的一種,其中每個結點的左孩子小於該結點的值,右孩子大於於該結點的值,對該樹進行中序遍歷可以得到一組有序序列

//二叉搜索樹

#include <stdio.h>

typedef struct node {
    int data;
    struct node *lchild;
    struct node *rchild;
} Node;

typedef struct tree {
    Node *root;
} Tree;

void insert(Tree *tree, int value) {
    Node *node = malloc(sizeof(Node));
    node->data = value;
    node->lchild = NULL;
    node->rchild = NULL;

    if (tree->root == NULL) {
        tree->root = node;
    }
    else {
        Node *temp = tree->root;

//有問題待查
//        while (temp != NULL) {
//            if (value > temp->data) {
//                temp = temp->rchild;
//            }
//            if (value < temp->data) {
//                temp = temp->lchild;
//            }
//        }
//        temp = node;

        while (temp != NULL) {
            if (value > temp->data) {
                if (temp->rchild == NULL) {
                    temp->rchild = node;
                    return;
                }
                else {
                    temp = temp->rchild;
                }
            }
            if (value < temp->data) {
                if (temp->lchild == NULL) {
                    temp->lchild = node;
                    return;
                }
                else {
                    temp = temp->lchild;
                }
            }
        }

    }
}

void preOrder(Node *node) {
    if (node == NULL) {
        return;
    }
    printf("%d\n", node->data);
    preOrder(node->lchild);
    preOrder(node->rchild);
}

void inOrder(Node *node) {
    if (node == NULL) {
        return;
    }
    inOrder(node->lchild);
    printf("%d\n", node->data);
    inOrder(node->rchild);
}

void postOrder(Node *node) {
    if (node == NULL) {
        return;
    }
    postOrder(node->lchild);
    postOrder(node->rchild);
    printf("%d\n", node->data);

}

int get_height(Node *node) {
    if (node == NULL) {
        return 0;
    }
    int left = get_height(node->lchild);
    int right = get_height(node->rchild);
    if (right > left) {
        return right+1;
    }
    else {
        return left +1;
    }

}

int get_max(Node *node) {
    if (node == NULL) {
        return -1;
    }
    int max = node->data;
    int left = get_max(node->lchild);
    int right = get_max(node->rchild);
    if (max < left) {
        max = left;
    }
    if (max < right) {
        max = right;
    }
    return max;
}

int main() {
    int arr[7] = {6, 3, 8, 2, 5, 1, 7};
    int i;
    Tree T,*tree = malloc(sizeof(Tree)); 
    tree->root = T.root = NULL;
    for (i = 0; i < 7; i++) {
        insert(tree, arr[i]);
    }

    inOrder(tree->root);
    printf("\nh = %d", get_height(tree->root));
    printf("\nMAX = %d\n", get_max(tree->root));
    return 0;
}

 

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章