#include<bits/stdc++.h> #define INF 0x3f3f3f3f3f3f3f3f #define mod 1000000007 #define IOS ios::sync_with_stdio(false) #define endl '\n' using namespace std; typedef long long ll; const int maxn = 1e5 + 10; typedef struct Node { int data; Node* left, * right; }node; void preorder(Node *node) {//前序遍历 if (node != NULL) { printf("%d\n", node->data); preorder(node->left); preorder(node->right); } } void inorder(Node* node) {//中序遍历 if (node != NULL) { inorder(node->left); printf("%d\n", node->data); inorder(node->right); } } void postorder(Node* node) {//后序遍历 if (node != NULL) { postorder(node->left); postorder(node->right); printf("%d\n", node->data); } } int main() { node n1, n2, n3, n4, n5, n6, n7; //暴力建树// n1.data = 1; n2.data = 2; n3.data = 3; n4.data = 4; n5.data = 5; n6.data = 6; n7.data = 7; n1.left = &n2; n1.right = &n3; n2.right = &n5; n2.left = &n4; n3.left = &n6; n3.right = &n7; n4.left = NULL; n4.right = NULL; n5.left = NULL; n5.right = NULL; n6.right = NULL; n6.left = NULL; n7.right = NULL; n7.left = NULL; preorder(&n1); printf("\n"); inorder(&n1); printf("\n"); postorder(&n1); }
前序遍历输出
1 2 4 5 3 6 7
中序遍历输出
4 2 5 1 6 3 7
后序遍历输出
4 5 2 6 7 3 1