#include
#include
typedef struct BinaryTreeNode
{
int data;
struct BinaryTreeNode *Left;
struct BinaryTreeNode *Right;
}Node;
//創(chuàng)建二叉樹(shù),順序依次為中間節(jié)點(diǎn)->左子樹(shù)->右子樹(shù)
Node* createBinaryTree()
{
Node *p;
int ch;
printf("輸入data");
scanf("%d",&ch);
if(ch == 0) //如果到了葉子節(jié)點(diǎn),接下來(lái)的左、右子樹(shù)分別賦值為0
{
p = NULL;
}
else
{
p = (Node*)malloc(sizeof(Node));
p->data = ch;
p->Left = createBinaryTree(); //遞歸創(chuàng)建左子樹(shù)
p->Right = createBinaryTree(); //遞歸創(chuàng)建右子樹(shù)
}
return p;
}
//先序遍歷
void preOrderTraverse(Node* root)
{
if( root )
{
printf("%d",root->data);
preOrderTraverse(root->Left);
preOrderTraverse(root->Right);
}
}
//中序遍歷
void inOrderTraverse(Node* root)
{
if( root )
{
inOrderTraverse(root->Left);
printf("%d",root->data);
inOrderTraverse(root->Right);
}
}
//后序遍歷
void lastOrderTraverse(Node* root)
{
if( root )
{
lastOrderTraverse(root->Left);
lastOrderTraverse(root->Right);
printf("%d",root->data);
}
}
//二叉樹(shù)節(jié)點(diǎn)總數(shù)目
int Nodenum(Node* root)
{
if(root == NULL)
{
return 0;
}
else
{
return 1+Nodenum(root->Left)+Nodenum(root->Right);
}
}
//二叉樹(shù)葉子節(jié)點(diǎn)數(shù)
int Leafnum(Node* root)
{
if(!root)
{
return 0;
}
else if( (root->Left == NULL) && (root->Right == NULL) )
{
return 1;
}
else
{
return (Leafnum(root->Left) + Leafnum(root->Right)) ;
}
}
int main()
{
int i;
Node *root = NULL;
root = createBinaryTree();
printf("二叉樹(shù)建立成功");
printf("\n");
preOrderTraverse(root);
printf("\n");
inOrderTraverse(root);
printf("\n");
lastOrderTraverse(root);
printf("\n");
i = Leafnum(root);
printf("%d",i);
printf("\n");
i = Nodenum(root);
printf("%d",i);
return 0;
}
當(dāng)前題目:普通二叉樹(shù)的建立
分享鏈接:
http://weahome.cn/article/goispc.html