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 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 | #include <stdio.h> #include <stdlib.h> #include <memory.h> typedef struct TreeNode { int data; struct TreeNode *left, *right; } TreeNode; TreeNode n1 = { 27, NULL, NULL }; TreeNode n2 = { 34, NULL, NULL }; TreeNode n3 = { 5, NULL, NULL }; TreeNode n4 = { 7, NULL, NULL }; TreeNode n5 = { 78, NULL, NULL }; TreeNode n6 = { 20, NULL, NULL }; TreeNode n7 = { '+', &n1, &n2 }; TreeNode n8 = { '*', &n7, &n3 }; TreeNode n9 = { '-', &n5, &n6}; TreeNode n10 = { '/', &n4, &n9 }; TreeNode n11 = { '-', &n8, &n10 }; TreeNode *root = &n11; int get_height(TreeNode *node) { int height = 0; if (node != NULL) height = 1 + max(get_height(node->left), get_height(node->right)); return height; } int get_leaf_count(TreeNode *node) { int count = 0; if (node != NULL) { if (node->left == NULL && node->right == NULL) return 1; else count = get_leaf_count(node->left) + get_leaf_count(node->right); } return count; } int get_node_count(TreeNode *node) { int count = 0; if (node != NULL) count = 1 + get_node_count(node->left) + get_node_count(node->right); return count; } inorder(TreeNode *root) { if (root) { int d = root->data; // ³ëµå ¹æ¹® if(root->left != NULL || root->right != NULL) printf("("); inorder(root->left); // ¿ÞÂʼºêÆ®¸® ¼øȸ if (d == '+' || d == '-' || d == '*' || d == '/') printf(" %c ", d); else printf(" %d ", d); inorder(root->right); // ¿À¸¥ÂʼºêÆ®¸® ¼øȸ if (root->left != NULL || root->right != NULL) printf(")"); } } double evaluate(TreeNode *root) { if (root == NULL) return 0; if (root->left == NULL && root->right == NULL)return root->data; else { double op1 = evaluate(root->left); double op2 = evaluate(root->right); printf("(%10lf %c %10lf)À» °è»êÇÕ´Ï´Ù.\n", op1, root->data, op2); switch (root->data) { case '+': return op1 + op2; case '-': return op1 - op2; case '*': return op1 * op2; case '/': return (double)op1 / (double)op2; } } return 0; } int main(void) { printf("Æ®¸®ÀÇ ³ôÀÌ: %d \n", get_height(root)); printf("Æ®¸®ÀÇ ´Ü¸»³ëµå °³¼ö: %d \n", get_leaf_count(root)); printf("Æ®¸®ÀÇ Àüü³ëµå °³¼ö: %d \n\n", get_node_count(root)); printf("¼øȯȣÃâ·Î ÁßÀ§ ¼øȸ \n"); inorder(root); printf("\n\n"); printf("¼ö½ÄÆ®¸® °è»ê °á°ú: %lf\n", evaluate(root)); } | cs |