二叉排序树

#include <stdio.h>
#include <stdlib.h>

typedef struct node
{
int data;
node *lchild;
node *rchild;
}TreeNode;

void InsertNode(TreeNode *&Node, int n)
{
if (Node == NULL)
{
Node = (TreeNode*)malloc(sizeof(TreeNode));
Node->data = n;
Node->lchild = Node->rchild = NULL;
}
else
{
if (Node->data > n)
{
InsertNode(Node->lchild, n);
}
else
{
InsertNode(Node->rchild, n);
}
}
}
//中序遍历
void in(TreeNode *Node)
{
int top = -1;
TreeNode *Stack[100];
TreeNode *p = Node;
do
{
while(p != NULL)
{
Stack[++top] = p;
p = p->lchild;
}
printf("%d ", Stack[top]->data);
p = Stack[top--];
if (p != NULL)
{
p = p->rchild;
}
} while (top >= 0 || p != NULL);
printf("\n");
}

int _tmain(int argc, _TCHAR* argv[])
{
TreeNode *Node = NULL;
int n;
scanf("%d", &n);
for (int i = 0; i < n; i++)
{
int data;
scanf("%d", &data);
InsertNode(Node, data);
}
in(Node);
return 0;
}

 

posted on 2013-04-15 21:15  lzm风雨无阻  阅读(156)  评论(0编辑  收藏  举报

导航