题目:输入一个整数和一棵二元树。从树的根结点开始往下访问一直到叶结点所经过的所有结点形成一条路径。打印出和与输入整数相等的所有路径。
如:
输入整数25,则输出 10 7 8;10 15
输入整数22,则输出 10 7 5
思路是运用前序遍历的递归方法,访问这课二叉树,在访问的同时,用一个栈来存放每个节点的数据,这样,当到达叶子节点是就判断其和是不是与输入的整数相等,相等的话就遍历这个栈。解题的难点就是存储路径,一开始的想法是复制节点,构造一个只用到左子树的单链表来存储,不过,感觉这样做下去会很繁琐,所以就换成构造栈来存储数据。这样通过递归的方法来push与pop数据,很般配。
要注意的是,下面在构造二叉树时,构造的是查找二叉树。。。
1 #include<stdio.h> 2 #include<stdlib.h> 3 #define M 100 4 #define m 10 5 struct BinaryTreeNode{ 6 int data; 7 BinaryTreeNode* leftTree; 8 BinaryTreeNode* rightTree; 9 }; 10 struct Stack{ 11 int top; 12 int tail; 13 int* stack; 14 }; 15 void InitStack(Stack& s){ 16 s.top = 0; 17 s.tail = 0; 18 s.stack = (int*)malloc(sizeof(int)*M); 19 } 20 void push(Stack& s,int data){ 21 if(s.top - s.tail >= M){ 22 s.stack =(int*) realloc(s.stack,m); 23 if(!s.stack) 24 return ; 25 } 26 s.stack[s.top++] = data; 27 } 28 int pop(Stack& s){ 29 if(s.top == s.tail) 30 return 0; 31 return s.stack[--s.top]; 32 } 33 void PrintStack(Stack s){ 34 printf("输出的路径是:"); 35 for(int i = s.tail; i < s.top; i++) 36 printf("%4d",s.stack[i]); 37 } 38 void DestoryStack(Stack s){ 39 free(s.stack); 40 } 41 void valueRoad(BinaryTreeNode* node,Stack& s,int data){ 42 if(!node) 43 return ; 44 data -= node->data; 45 push(s,node->data); 46 if((!node->leftTree)&&(!node->rightTree)){ 47 if(!data){ 48 PrintStack(s); 49 printf(" "); 50 } 51 } 52 valueRoad(node->leftTree,s,data); 53 valueRoad(node->rightTree,s,data); 54 pop(s); 55 } 56 void buildBinaryTree(BinaryTreeNode*& head){ 57 int data; 58 printf("输入数据(0结束) "); 59 scanf("%d",&data); 60 if(!data) 61 return ; 62 if(!head){ 63 head = (BinaryTreeNode*)malloc(sizeof(BinaryTreeNode)); 64 head->data = data; 65 head->leftTree = NULL; 66 head->rightTree = NULL; 67 } 68 BinaryTreeNode* current = head; 69 printf("输入数据(0结束) "); 70 scanf("%d",&data); 71 while(data){ 72 while(current){ 73 if(data >= current->data) 74 if(current->rightTree) 75 current = current->rightTree; 76 else { 77 current->rightTree = (BinaryTreeNode*)malloc(sizeof(BinaryTreeNode)); 78 current = current->rightTree; 79 break; 80 } 81 else { 82 if(current->leftTree) 83 current = current->leftTree; 84 else { 85 current->leftTree = (BinaryTreeNode*)malloc(sizeof(BinaryTreeNode)); 86 current = current->leftTree; 87 break; 88 } 89 } 90 } 91 current->data = data; 92 current = head; 93 printf("输入数据(0结束) "); 94 scanf("%d",&data); 95 } 96 } 97 void freeBinaryTree(BinaryTreeNode* head){ 98 if(!head) 99 return ; 100 if(head->leftTree) 101 freeBinaryTree(head->leftTree); 102 if(head->rightTree) 103 freeBinaryTree(head->rightTree); 104 printf("%4d",head->data); 105 free(head); 106 } 107 int main(){ 108 BinaryTreeNode* head = NULL; 109 BinaryTreeNode* current = NULL; 110 int data; 111 Stack s; 112 InitStack(s); 113 buildBinaryTree(head); 114 printf("输入要求数据: "); 115 scanf("%d",&data); 116 valueRoad(head,s,data); 117 DestoryStack(s); 118 freeBinaryTree(head); 119 return 0; 120 }