每日算法三道之根据二叉树的前中序遍历结果求后序遍历

核心思想:递归,分冶
思路: 可根据前序遍历先确定根节点,在中序遍历中确定此根节点的位置,从而可以将前序和中序遍历结果分为两部分,再依次递归左边部分和右边部分,输出根节点值。
代码

/*********************
功能:根据前中序二叉树的遍历结果求后序遍历结果
@athor:rly
@date:2018-3-6
**********************/

#include <iostream>
using namespace std;
bool PreIn2Post(char *pre, char *in, char *post, int len, int index)
{
    if (pre == NULL || in == NULL || len <= 0)
    {
        return false;
    }
    if (len == 1)
    {
        *(post + index) = *pre;
        index++;
        return true;
    }
    char *root = pre;
    int inRoot;
    for (inRoot = 0; inRoot < len; inRoot++)
    {
        if (*(in + inRoot) == *root)
        {
            break;
        }
    }                                                      //inRoot位置其实就表示了当前根的左子树有多少个节点
    PreIn2Post(pre + 1, in, post, inRoot, index);
    PreIn2Post(pre + inRoot + 1, in + inRoot + 1, post,len - (inRoot + 1), index);
    *(post + index) = *root;
    index++;
}

猜你喜欢

转载自blog.csdn.net/rlyhaha/article/details/79476489