普通二叉树的遍历及求节点个数
#include <stdio.h>
#include <stdlib.h>
#include <assert.h>
typedef int BTDataType;
typedef struct BinaryTreeNode
{
BTDataType data;
struct BinaryTreeNode* left;
struct BinaryTreeNode* right;
}BTNode;
static BTNode* BuyNode(BTDataType x)
{
BTNode* node = (BTNode*)malloc(sizeof(BTNode));
assert(node);
node->data = x;
node->left = NULL;
node->right = NULL;
return node;
}
static BTNode* CreateBinaryTree()
{
BTNode* node1 = BuyNode(1);
BTNode* node2 = BuyNode(2);
BTNode* node3 = BuyNode(3);
BTNode* node4 = BuyNode(4);
BTNode* node5 = BuyNode(5);
BTNode* node6 = BuyNode(6);
node1->left = node2;
node1->right = node4;
node2->left = node3;
node4->left = node5;
node4->right = node6;
return node1;
}
void PreOrder(BTNode* root)
{
if (NULL==root)
{
printf("# ");
return;
}
printf("%d ",root->data);
PreOrder(root->left);
PreOrder(root->right);
}
void InOrder(BTNode* root)
{
if (NULL == root)
{
printf("# ");
return;
}
InOrder(root->left);
printf("%d ", root->data);
InOrder(root->right);
}
void PostOrder(BTNode* root)
{
if (NULL == root)
{
printf("# ");
return;
}
PostOrder(root->left);
PostOrder(root->right);
printf("%d ", root->data);
}
int count = 0;
void TreeSize1(BTNode* root)
{
if (NULL==root)
{
return;
}
count++;
TreeSize1(root->left);
TreeSize1(root->right);
}
int TreeSize2(BTNode* root)
{
if (NULL==root)
{
return 0;
}
return TreeSize2(root->left) + TreeSize2(root->right)+1;
}
int TreeLeafSize(BTNode* root)
{
if (NULL==root)
{
return 0;
}
if (NULL==root->left && NULL==root->right)
{
return 1;
}
return TreeLeafSize(root->left) + TreeLeafSize(root->right);
}
int TreeKLevel(BTNode* root,int k)
{
assert(k>=1);
if (NULL==root)
return 0;
if (1 == k)
return 1;
return TreeKLevel(root->left,k-1) + TreeKLevel(root->right,k-1);
}
int TreeDepth(BTNode* root)
{
if (NULL == root)
return 0;
int ret1 = TreeDepth(root->left);
int ret2 = TreeDepth(root->right);
if (ret1>=ret2)
{
return ret1 + 1;
}
else
{
return ret2 + 1;
}
}
BTNode* TreeFind(BTNode* root, BTDataType x)
{
if (NULL == root)
return NULL;
if (x==root->data)
return root;
BTNode* ret1 = TreeFind(root->left,x);
if (ret1)
return ret1;
BTNode* ret2 = TreeFind(root->right, x);
if (ret2)
return ret2;
return NULL;
}
int main()
{
BTNode* root = CreateBinaryTree();
PreOrder(root);
printf("\n");
InOrder(root);
printf("\n");
PostOrder(root);
printf("\n");
count = 0;
TreeSize1(root);
printf("TreeSize:%d\n",count);
printf("TreeSize:%d\n", TreeSize2(root));
printf("TreeLeafSize:%d\n", TreeLeafSize(root));
printf("TreeKLevel:%d\n", TreeKLevel(root, 3));
printf("TreeDepth:%d\n", TreeDepth(root));
TreeFind(root, 5);
return 0;
}