1 #include <stdio.h> 2 #include <stdlib.h> 3 /*在二叉樹中找出和爲某值的全部路徑*/ 4 /*從樹的根節點開始往下訪問一直到葉節點所通過的全部節點造成一條路徑*/ 5 /*分析,二叉樹確定要遞歸,遍歷每條路徑,獲得每條路徑和。 6 *路徑的存儲用棧結構比較合適,鏈表,數組均可。 7 */ 8 typedef struct node{ 9 int value; 10 struct node *left; 11 struct node *right; 12 }node; 13 14 static int total; 15 #define STACK_SIZE 100 16 static int stack[STACK_SIZE], top_element = -1; 17 18 int is_empty() 19 { 20 return top_element == -1; 21 } 22 int is_full() 23 { 24 return top_element == STACK_SIZE-1; 25 } 26 void push(int value) 27 { 28 if(is_full()){ 29 printf("stack is full.\n"); 30 return; 31 } 32 top_element++; 33 stack[top_element] = value; 34 } 35 void pop() 36 { 37 if(is_empty()){ 38 printf("stack is empty.\n"); 39 return; 40 } 41 top_element--; 42 } 43 int top() 44 { 45 if(is_empty()){ 46 printf("stack is empty.\n"); 47 exit(0); 48 } 49 return stack[top_element]; 50 } 51 52 void top_all() 53 { 54 if(is_empty()){ 55 printf("stack is empty.\n"); 56 exit(0); 57 } 58 int i; 59 60 for(i = 0; i <= top_element; i++) 61 printf("%d ", stack[i]); 62 printf("\n"); 63 } 64 65 void build_tree(node **tree, int value) 66 { 67 if(*tree == NULL){ 68 (*tree) = calloc(1, sizeof(node)); 69 if(*tree == NULL){ 70 perror("malloc failure:"); 71 return; 72 } 73 (*tree)->value = value; 74 }else if((*tree)->value > value) 75 build_tree(&(*tree)->left, value); 76 else if((*tree)->value == value) 77 ; 78 else 79 build_tree(&(*tree)->right, value); 80 } 81 void read_tree(node *tree) 82 { 83 if(tree == NULL) 84 return; 85 if(tree->left != NULL) 86 read_tree(tree->left); 87 printf("%d\n", tree->value); 88 if(tree->right != NULL) 89 read_tree(tree->right); 90 } 91 /*路徑,需前序遍歷,先根節點,左右。 92 *理解遍歷過程,適時減去加上節點值。 93 */ 94 void read_tree2(node *tree, int size) 95 { 96 if(tree == NULL) 97 return; 98 99 total += tree->value; 100 push(tree->value); 101 if(tree->left == NULL && tree->right == NULL) 102 if(total == size) 103 top_all(); 104 105 if(tree->left != NULL) 106 read_tree2(tree->left, size); 107 108 if(tree->right != NULL) 109 read_tree2(tree->right, size); 110 111 total -= tree->value; 112 pop(tree->value); 113 } 114 int main(void) 115 { 116 node *tree = NULL; 117 118 build_tree(&tree, 10); 119 build_tree(&tree, 12); 120 build_tree(&tree, 5); 121 build_tree(&tree, 4); 122 build_tree(&tree, 7); 123 124 read_tree2(tree, 22); 125 126 return 0; 127 }