标签:
1 #include<stdio.h> 2 #include<stdlib.h> 3 4 struct tNode 5 { 6 int data; 7 struct tNode* left; 8 struct tNode* right; 9 }; 10 11 void MorrisTraversal(struct tNode *root) 12 { 13 struct tNode *current,*pre; 14 15 if(root == NULL) 16 return; 17 18 current = root; 19 while(current != NULL) 20 { 21 if(current->left == NULL) 22 { 23 printf(" %d ", current->data); 24 current = current->right; 25 } 26 else 27 { 28 /* 找到current的前驱节点 */ 29 pre = current->left; 30 while(pre->right != NULL && pre->right != current) 31 pre = pre->right; 32 33 /* 将current节点作为其前驱节点的右孩子 */ 34 if(pre->right == NULL) 35 { 36 pre->right = current; 37 current = current->left; 38 } 39 40 /* 恢复树的原有结构,更改right 指针 */ 41 else 42 { 43 pre->right = NULL; 44 printf(" %d ",current->data); 45 current = current->right; 46 } /* End of if condition pre->right == NULL */ 47 } /* End of if condition current->left == NULL*/ 48 } /* End of while */ 49 } 50 51 struct tNode* newtNode(int data) 52 { 53 struct tNode* tNode = (struct tNode*) 54 malloc(sizeof(struct tNode)); 55 tNode->data = data; 56 tNode->left = NULL; 57 tNode->right = NULL; 58 59 return(tNode); 60 } 61 62 /* 测试*/ 63 int main() 64 { 65 66 /* 构建树结构如下: 67 1 68 / 69 2 3 70 / 71 4 5 72 */ 73 struct tNode *root = newtNode(1); 74 root->left = newtNode(2); 75 root->right = newtNode(3); 76 root->left->left = newtNode(4); 77 root->left->right = newtNode(5); 78 79 MorrisTraversal(root); 80 return 0; 81 }
标签:
原文地址:http://www.cnblogs.com/tao-alex/p/5894348.html