二叉樹的基本操作
sunmenggmail發表於2012-04-16
-
轉自:http://blog.csdn.net/randyjiawenjie/article/details/6329712
-
void insert(tNode root,int data)
-
{
-
tNode newNode = (tNode)malloc(sizeof(treeNode));
-
newNode->data = data;
-
newNode->lchild = NULL;
-
newNode->rchild = NULL;
-
tNode current = root;
-
tNode parent;
-
while (1)
-
{
-
parent = current;
-
if (current->data > newNode->data)
-
{
-
current = current->lchild;
-
if (current == NULL)
-
{
-
parent->lchild = newNode;
-
return;
-
}
-
}
-
else
-
{
-
current = current->rchild;
-
if (current == NULL)
-
{
-
parent->rchild = newNode;
-
return;
-
}
-
}
-
}
-
}
-
-
-
-
void preOrder(tNode root)
-
{
-
if (root != NULL)
-
{
-
preOrder(root->lchild);
-
printf("%d ",root->data);
-
preOrder(root->rchild);
-
}
-
}
-
-
-
-
int getLeaf(tNode root)
-
{
-
if (root == NULL)
-
return 0;
-
else
-
if (root->lchild == NULL && root->rchild == NULL)
-
return 1;
-
else
-
return getLeaf(root->lchild) + getLeaf(root->rchild);
-
}
-
-
-
-
int getDepth(tNode root)
-
{
-
if (root == NULL)
-
return 0;
-
else
-
return getDepth(root->lchild) > getLeaf(root->rchild)? 1 + getDepth(root->lchild): 1 + getDepth(root->rchild);
-
-
-
-
-
-
}
-
int main()
-
{
-
tNode root = (tNode)malloc(sizeof(treeNode));
-
root->data = 10;
-
root->lchild = NULL;
-
root->rchild = NULL;
-
-
insert(root,5);
-
insert(root,15);
-
insert(root,1);
-
insert(root,8);
-
insert(root,20);
-
insert(root,12);
-
preOrder(root);
-
printf("/n");
-
int numleaf = getLeaf(root);
-
printf("%d/n", numleaf);
-
int depth = getDepth(root);
-
printf("%d/n",depth);
-
return 0;
-
}