这个代码输出有问题,但是我问了很多同学也找不出来
这是输出结果
Pre-order Traversal: 1 2 4 5 3 6 7
In-order Traversal: 4 2 5 1 6 3 7
Post-order Traversal: 5
后序的只有一个数字
#include <stdio.h>
#include <stdlib.h>
typedef struct Node {
int data;
struct Node *left, *right;
int isThreaded;
} Node;
Node *newNode(int data) {
Node *temp = (Node *)malloc(sizeof(Node));
temp->data = data;
temp->left = temp->right = NULL;
temp->isThreaded = 0;
return temp;
}
void inOrderTraversal(Node *root) {
if (!root) return;
Node *current = root;
while (current) {
if (!current->left) {
printf("%d ", current->data);
current = current->right;
} else {
Node *pre = current->left;
while (pre->right && pre->right != current) {
pre = pre->right;
}
if (!pre->right) {
pre->right = current;
current = current->left;
} else {
pre->right = NULL;
printf("%d ", current->data);
current = current->right;
}
}
}
}
void preOrderTraversal(Node *root) {
if (!root) return;
Node *current = root;
while (current) {
if (!current->left) {
printf("%d ", current->data);
current = current->right;
} else {
Node *pre = current->left;
while (pre->right && pre->right != current) {
pre = pre->right;
}
if (!pre->right) {
printf("%d ", current->data);
pre->right = current;
current = current->left;
} else {
pre->right = NULL;
current = current->right;
}
}
}
}
void postOrderTraversal(Node* root) {
if (!root) return;
Node* dummy = newNode(-1);
dummy->left = root;
Node* current = dummy;
while (current) {
if (!current->left) {
current = current->right;
}
else {
Node* pre = current->left;
while (pre->right && pre->right != current) {
pre = pre->right;
}
if (!pre->right) {
pre->right = current;
current = current->left;
}
else {
// Reverse the nodes from current->left to pre
Node* first = current->left;
Node* middle = first->right;
Node* last;
while (middle != current) {
last = middle->right;
middle->right = first;
middle->isThreaded = 1; // set the isThreaded flag to 1
first = middle;
middle = last;
}
// Print the reversed nodes
first = pre;
while (first != current->left) {
printf("%d ", first->data);
first = first->right;
}
// Re-reverse the nodes to restore the tree
first = current->left;
middle = first->right;
while (middle != current) {
last = middle->right;
middle->right = first;
middle->isThreaded = 0; // set the isThreaded flag to 0
first = middle;
middle = last;
}
pre->right = NULL;
current = current->right;
}
}
}
free(dummy);
}
int main() {
Node *root = newNode(1);
root->left = newNode(2);
root->right = newNode(3);
root->left->left = newNode(4);
root->left->right = newNode(5);
root->right->left = newNode(6);
root->right->right = newNode(7);
printf("Pre-order Traversal: ");
preOrderTraversal(root);
printf("\nIn-order Traversal: ");
inOrderTraversal(root);
printf("\nPost-order Traversal: ");
postOrderTraversal(root);
printf("\n");
return 0;
}