已知二叉树前、中序遍历,求后序 / 已知二叉树中、后序遍历,求前序

void solve(int start,int end,int root) { // 前序和中序 -> 后序
    // 每次调用solve()函数,传入pre-order的start,end,root
    if (start > end) // 递归边界
        return;
    int i = start;
    while (i < end && in.at(i) != pre.at(root)) // 找到左右子树的分割点
        i++;
    solve(start, i - 1, root + 1);
    solve(i + 1, end, root + i - start + 1);
    post.push_back(pre.at(root));
}
 


void solve(int start,int end,int root) { // 后序和中序 -> 前序
    // 每次调用solve()函数,传入post-order的start,end,root
    if (start > end) // 递归边界
        return;
    int i = start;
    while (i < end && in.at(i) != post.at(root)) // 找到左右子树的分割点
        i++;
    pre.push_back(post.at(root));
    solve(start, i - 1, root - (end - i) - 1);
    solve(i + 1, end, root - 1);
}

 

posted @ 2017-03-12 20:19  codinRay  阅读(320)  评论(0编辑  收藏  举报