typedef struct BSTree{
int data;
BSTree *pLeft;
BSTree *pRight;
}Node;
Node * BuyNewNode(int num)
{
Node * pNode = new(Node);
//assert(pNode);
pNode->data = num;
pNode->pLeft = NULL;
pNode->pRight = NULL;
return pNode;
}
Node * insert(int num, Node * root) {
if (root == NULL) {
root = BuyNewNode(num);
} else {
if (num > root->data)
root->pRight = insert(num,root->pRight);
else if (num < root->data)
root->pLeft= insert(num,root->pLeft);
}
return root;
}
int main()
{
int input[10] = {10,6,14,4,8,12,16,5,7,13};
Node *root = NULL;
Node *Head = NULL;
for(int i = 0; i<10; i++) {
root = insert(input[i],root);
if (i==0)
Head = root;
}
return 0;
}
中序遍历递归程序如下:
void link(Node *root) {
if(root == NULL)
return;
if(root->pLeft) { // 1.
link(root->pLeft);
}
printf("%d ", root->data); // 2.
if(root->pRight) { // 3.
link(root->pRight);
}
}
只要把中序的语句调一下顺序就是前序遍历和后序遍历
前序:2->1->3
后序:1->3->2