给我用C语言写一个二叉树的遍历
时间: 2023-03-09 11:30:31 浏览: 138
我可以给你一个例子: #include <stdio.h>
struct node
{
int data;
struct node *left, *right;
}; /* function to print leaf nodes of a binary tree*/
void printLeaves(struct node* root)
{
if ( root != NULL )
{
printLeaves(root->left);
// 如果节点为叶子节点,则打印
if ( root->left == NULL && root->right == NULL )
printf("%d ", root->data);
printLeaves(root->right);
}
}
/* function to print left boundry of a binary tree*/
void printBoundaryLeft(struct node* root)
{
if ( root != NULL )
{
if ( root->left )
{
// to ensure top down order, print the node
// before calling itself for left subtree
printf("%d ", root->data);
printBoundaryLeft(root->left);
}
else if( root->right )
{
printf("%d ", root->data);
printBoundaryLeft(root->right);
}
}
} /* function to print right boundry of a binary tree */
void printBoundaryRight(struct node* root)
{
if ( root != NULL )
{
if ( root->right )
{
// to ensure bottom up order, first call for
// right subtree, then print this node
printBoundaryRight(root->right);
printf("%d ", root->data);
}
else if ( root->left )
{
printBoundaryRight(root->left);
printf("%d ", root->data);
}
}
} /* A function to do boundary traversal of a given binary tree*/
void printBoundary (struct node* root)
{
if (root)
{
printf("%d ",root->data);
// 先遍历左边界
printBoundaryLeft(root->left);
// 再遍历叶子节点
printLeaves(root->left);
printLeaves(root->right);
// 最后遍历右边界
printBoundaryRight(root->right);
}
}
阅读全文