树的后序遍历方式源码

#include <stdio.h>
#include <stdlib.h>
typedef struct node{
    char data;
    struct node *llink;
    struct node *rlink;
}NODE;
NODE*build()//
{
    NODE *tree;
    char c;
    scanf("%c",&c);
    if(c=='#') tree = NULL;
    else
    {
        tree=(NODE*)malloc(sizeof(NODE));
        tree->data=c;
        tree->llink=build();
        tree->rlink=build();
    }
    return tree;
}
void houxu(NODE*tree)
{
    NODE*pt=tree;
    int tt[100],top=-1;
    NODE*s[100];
    do
    {
        while(pt!=NULL)
        {
            s[++top]=pt;
            tt[top]=0;
            pt=pt->llink;
        }
        if(top>=0)
        {
            if(!tt[top])
            {
                pt=s[top];
                tt[top]=1;
                pt=pt->rlink;
            }
            else printf("%c",s[top--]->data);
        }
    }while((pt!=NULL)||(top!=-1));
}
int main()
{
    printf("请输入树的结点:\n");
    NODE*tree=(NODE*)malloc(sizeof(NODE));
    tree=build();
    printf("后序遍历的结果是:\n");
    houxu(tree);
    printf("\n");
    return 0;
}
/*测试数据
abd##e##cf###
输出:debfca
*/
思路: 首先,我们需要定义一个二叉的结构体,包含一个数据域和左右子指针。然后,我们可以使用递归的方式来实现二叉的遍历。 先序遍历的算法:先输出当前节点的值,再遍历左子,最后遍历右子。 中序遍历的算法:先遍历左子,再输出当前节点的值,最后遍历右子后序遍历算法:先遍历左子,再遍历右子,最后输出当前节点的值。 源码: ``` #include <stdio.h> #include <stdlib.h> // 定义二叉树结构体 typedef struct TreeNode { int val; struct TreeNode *left; struct TreeNode *right; } TreeNode; // 先序遍历 void preorder(TreeNode *root) { if (root == NULL) return; printf("%d ", root->val); preorder(root->left); preorder(root->right); } // 中序遍历 void inorder(TreeNode *root) { if (root == NULL) return; inorder(root->left); printf("%d ", root->val); inorder(root->right); } // 后序遍历 void postorder(TreeNode *root) { if (root == NULL) return; postorder(root->left); postorder(root->right); printf("%d ", root->val); } // 创建二叉 TreeNode* createTree() { int val; scanf("%d", &val); if (val == -1) return NULL; TreeNode *root = (TreeNode*)malloc(sizeof(TreeNode)); root->val = val; root->left = createTree(); root->right = createTree(); return root; } int main() { TreeNode *root = createTree(); printf("先序遍历:"); preorder(root); printf("\n中序遍历:"); inorder(root); printf("\n后序遍历:"); postorder(root); return 0; } ``` 结论: 通过以上代码,我们可以实现二叉的先序、中序、后序遍历算法。在主函数中调用函数遍历输出二叉的每个节点的值。
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值