您的位置:首页 > 其它

二叉排序树

2013-04-15 21:15 183 查看
#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;
}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: