1 #include<iostream> 2 using namespace std; 3 4 struct BinaryTreeNode 5 { 6 int m_nValue; 7 BinaryTreeNode * m_pLeft; 8 BinaryTreeNode * m_pRight; 9 //int tag; 10 }; 11 int foreOrder[8] = {1, 2, 4, 7, 3, 5, 6, 8}; 12 int inOrder[8] = {4, 7, 2, 1, 5, 3, 8, 6}; 13 int length = 8; 14 BinaryTreeNode * buildTree( int * i, int first, int last) 15 { 16 if((*i) >= length) return NULL; 17 int j; 18 for(j = 0; j < length; j++) 19 if(inOrder[j] == foreOrder[*i]) 20 break; 21 BinaryTreeNode * root = (BinaryTreeNode *)malloc(sizeof(BinaryTreeNode)); 22 root->m_nValue = foreOrder[*i]; 23 root->m_pLeft = NULL; 24 root->m_pRight = NULL; 25 *i += 1; 26 if(j > first) 27 root->m_pLeft = buildTree(i, first, j); 28 if(last > j+1) 29 root->m_pRight = buildTree(i, j+1, last); 30 return root; 31 } 32 //中序遍历 33 void inOrderOutput(BinaryTreeNode * root) 34 { 35 if(root == NULL) return; 36 inOrderOutput(root->m_pLeft); 37 printf("%d ", root->m_nValue); 38 inOrderOutput(root->m_pRight); 39 } 40 int main() 41 { 42 int i = 0; 43 BinaryTreeNode * root = buildTree(&i, 0, length); 44 inOrderOutput(root); 45 return 0; 46 }
相关文章: