创建一棵二叉树并输出节点
源代码:
1 #include<iostream> 2 using namespace std; 3 4 typedef struct BiTreeNode{ 5 int data; 6 struct BiTreeNode *left; 7 struct BiTreeNode *right; 8 }BiTreeNode; 9 10 //创建二叉树,使用前序创建二叉树,遇到-1表示节点为空 11 BiTreeNode* createTree() 12 { 13 int item; 14 BiTreeNode *t ; 15 cin>>item; 16 17 if(item != -1) 18 { 19 BiTreeNode *pTmpNode = new BiTreeNode(); 20 21 t = pTmpNode; 22 pTmpNode->data = item; 23 24 t->left = createTree(); 25 t->right = createTree(); 26 return t; 27 } 28 else 29 { 30 t = NULL; 31 return t; 32 } 33 } 34 35 void pre_order(BiTreeNode *r) 36 { 37 BiTreeNode *pTmpNode = r; 38 39 if(pTmpNode != NULL) 40 { 41 cout<<pTmpNode->data<<" "; 42 pre_order(pTmpNode->left); 43 pre_order(pTmpNode->right); 44 } 45 } 46 47 int main(){ 48 BiTreeNode *node; 49 node = createTree(); 50 pre_order(node); 51 return 0; 52 }