已知前序中序求后序-二叉树

writer:pprp

思路很容易理解,但是实现还是有一点难度,容易错

参考书目:《算法竞赛宝典》

代码如下:

//已知前序中序,求后序
#include <iostream>

using namespace std;

//a是前序,b是中序
void hwg(string a,string b)
{
    int ll,lr;

    for(unsigned int i = 0; i < b.length(); i++)
    {
        if(a[0] == b[i])    //找到根节点
        {
            ll = i;                   //分别计算出左右子树的长度
            lr = b.length()-1-ll;
            if(ll)                     //
            {
                string part1(a,1,ll),part2(b,0,11);
                hwg(part1,part2);
            }
            if(lr)
            {
                string part3(a,1+ll,lr),part4(b,1+ll,lr);
                hwg(part3,part4);
            }
            cout << a[0];
            break;
        }
    }
}

int main()
{
    string a,b;
    cout <<"请输入前序:"<<endl;
    cin >> a;
    cout <<"请输入中序:"<<endl;
    cin >> b;
    cout <<"后序为:"<<endl;
    hwg(a,b);
    return 0;
}

 

转载于:https://www.cnblogs.com/pprp/p/7220630.html

以下为 C 语言的二叉树已知前序中序后序的完整代码: ```c #include <stdio.h> #include <stdlib.h> // 定义二叉树节点 typedef struct node { char data; struct node *left; struct node *right; } TreeNode; // 递归构建二叉树 TreeNode* buildTree(char *preorder, char *inorder, int preStart, int preEnd, int inStart, int inEnd) { if (preStart > preEnd || inStart > inEnd) { return NULL; } // 获取前序遍历的根节点 TreeNode *root = (TreeNode*) malloc(sizeof(TreeNode)); root->data = preorder[preStart]; root->left = NULL; root->right = NULL; // 找到中序遍历中根节点的位置 int rootIndex; for (int i = inStart; i <= inEnd; i++) { if (inorder[i] == preorder[preStart]) { rootIndex = i; break; } } // 递归构建左子树和右子树 root->left = buildTree(preorder, inorder, preStart+1, preStart+rootIndex-inStart, inStart, rootIndex-1); root->right = buildTree(preorder, inorder, preStart+rootIndex-inStart+1, preEnd, rootIndex+1, inEnd); return root; } // 后序遍历输出二叉树 void postorderTraversal(TreeNode *root) { if (root == NULL) { return; } postorderTraversal(root->left); postorderTraversal(root->right); printf("%c", root->data); } int main(void) { char preorder[] = {'A', 'B', 'D', 'E', 'C', 'F'}; char inorder[] = {'D', 'B', 'E', 'A', 'F', 'C'}; TreeNode *root = buildTree(preorder, inorder, 0, 5, 0, 5); printf("后序遍历结果:"); postorderTraversal(root); printf("\n"); return 0; } ``` 以上代码实现了已知前序遍历和中序遍历构建二叉树,并输出后序遍历的结果。需要注意的是,代码中的前序遍历和中序遍历都是以字符数组的形式给出的,可以根据实际情况进行修改。
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值