Last active
September 27, 2015 04:43
-
-
Save wingyplus/db30b3e540a523040666 to your computer and use it in GitHub Desktop.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
#include <stdio.h> | |
#include <stdlib.h> | |
struct _Node { | |
struct _Node *left; | |
int val; | |
struct _Node *right; | |
}; | |
typedef struct _Node Node; | |
Node * NewNode(int val) { | |
Node *node = malloc(sizeof(Node)); | |
node->left = NULL; | |
node->val = val; | |
node->right = NULL; | |
return node; | |
} | |
void AddValue(Node *node, int val) { | |
if (val <= node->val) { | |
if (node->left == NULL) { | |
node->left = NewNode(val); | |
} else { | |
AddValue(node->left, val); | |
} | |
return; | |
} | |
if (node->right == NULL){ | |
node->right = NewNode(val); | |
} else { | |
AddValue(node->right, val); | |
} | |
return; | |
} | |
void DeleteNode(Node *node) { | |
if (node->left != NULL) { | |
DeleteNode(node->left); | |
} | |
if (node->right != NULL) { | |
DeleteNode(node->right); | |
} | |
free(node); | |
} | |
int main() { | |
Node *root = NewNode(2); | |
AddValue(root, 20); | |
AddValue(root, 1); | |
AddValue(root, 0); | |
AddValue(root, 21); | |
printf("main root %d\n", root->val); | |
printf("left root %d\n", root->left->val); | |
printf("right root %d\n", root->right->val); | |
printf("left of left root %d\n", root->left->left->val); | |
printf("right of right root %d\n", root->right->right->val); | |
DeleteNode(root); | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
typedef กับ struct มันรวมกันไปได้เลยนะครับ แล้วไม่ต้องใช้คนละชื่อได้ครับ
typedef struct Node {
struct Node *left;
int val;
struct Node *right;
} Node;