#include<iostream> using namespace std; struct node { int data; node* left; node* right; }; struct list { node* p; list* next; }; node * createTree() { node* root=NULL; int temp; list* head = (list*)malloc(sizeof(list)),*tail; tail = head; node* nodeCur=NULL, * nodeTemp=NULL; list* listCur = NULL,*listTemp = NULL; while (cin >> temp) { if (root == NULL) { root = (node*)malloc(sizeof(node)); root->left = NULL; root->right = NULL; root->data = temp; nodeCur = root; head->p = root; head->next = NULL; listCur = head; } else { nodeTemp = (node*)malloc(sizeof(node)); nodeTemp->data = temp; nodeTemp->left = NULL; nodeTemp->right = NULL; listTemp = (list*)malloc(sizeof(list)); listTemp->next = NULL; listTemp->p = nodeTemp; tail->next = listTemp; tail = listTemp; if (nodeCur->left == NULL) { nodeCur->left = nodeTemp; } else { nodeCur->right = nodeTemp; listCur = listCur->next; nodeCur = listCur->p; } } } return root; } void preOrder(node* root) { if (root == NULL) return; else { cout << root->data<<" "; preOrder(root->left); preOrder(root->right); } } int main() { node* root= createTree();; preOrder(root); }
建立二叉树前序打印一下,ctrl+z输入结束。