前序遍历:根左右
中序遍历:左根右
后序遍历:左右根
这三个遍历需要你掌握,特别在求职的时候可能会考有前序遍历求后序遍历
#include <stdio.h>
struct Node
{
int data;
struct Node *left;
struct Node *right;
};
typedef struct Node Node;
Node *CreateBSTree(Node *root, int num)
{
if (NULL == root)
{
root = (Node *)malloc(sizeof(Node) * 1);
if (NULL == root)
{
printf(“malloc fialure!\n”);
}
root->data = num;
root->left = NULL;
root->right = NULL;
return root;
}
else
{
if (num > root->data)
{
root->right = CreateBSTree(root->right, num);
}
else
{
root->left = CreateBSTree(root->left, num);
}
}
}
void MidOrderTree(Node *root)
{
if (NULL == root)
{
return;
}
MidOrderTree(root->left);
printf("%d ", root->data);
MidOrderTree(root->right);
}
int main()
{
Node *root = NULL;
int num, i;
for (i = 0; i < 10; i++)
{
scanf("%d", &num);
root = CreateBSTree(root, num);
}
MidOrderTree(root);
printf("\n");
return 0;
}