binaryTree (draft)

来源:互联网 发布:平安科技java面试题 编辑:程序博客网 时间:2024/05/17 06:36
//All Rights Reserved#include <stdio.h>#include <stdlib.h>struct node{int date;node *lchild, *rchild;};int getDepth(node *);int searchNode(node *);node *insertNode(node *, int);node *deleteNode(node *, int);void preorderTraversal(node *);void inorderTraversal(node *);void postorderTraversal(node *);int main(){node *root;root = (node *)malloc(sizeof(root));root->date = 5;root->lchild = NULL;root->rchild = NULL;int menu, data;while (1){printf("********** print menu **********\n");printf("please choose an operation: \n");printf("1: insert a node\n");printf("2: delete a node\n");printf("3: get tree depth\n");printf("4: NLR traversal\n");printf("0: exit!\n");printf("********** print menu **********\n\n");scanf("%d", &menu);if (menu==1){printf("please input a data: ");scanf("%d", &data);root = insertNode(root, data);}else if (menu == 2){printf("please input a data: ");scanf("%d", &data);deleteNode(root, data);}else if (menu == 3){printf("depth of tree: %d\n",getDepth(root));}else if (menu == 4){preorderTraversal(root);printf("\n");}else if (menu == 0)break;elseprintf("wrong parameter!\n");}return 0;}node *insertNode(node *N, int n){node *M, *T;M = N;T = (node *)malloc(sizeof(node));T->date = n;T->lchild = NULL;T->rchild = NULL;if (n == M->date)printf("node already exist!\n");else if (n < M->date)if (M->lchild != NULL)insertNode(M->lchild, n);elseM->lchild = T;else if (n > M->date)if (M->rchild != NULL)insertNode(M->rchild, n);elseM->rchild = T;return N;}node *deleteNode(node *N, int){return N;}int getDepth(node *N){int hl, hr, max;if (!N)return 0;else if (N->lchild == NULL && N->rchild == NULL)return 1;hl = getDepth(N->lchild);hr = getDepth(N->rchild);max = hl>hr ? hl : hr;return max+1;}// 5// / \// 2 7// / / \// 1 6 9void preorderTraversal(node *N){node *M;M = N;if (M){printf("%d ", M->date);if (M->lchild != NULL)preorderTraversal(M->lchild);if (M->rchild != NULL)preorderTraversal(M->rchild);}elseprintf("This is a null binary tree\n");}

原创粉丝点击