由二叉树的后序和中序求先序

来源:互联网 发布:刷mac os 编辑:程序博客网 时间:2024/06/08 18:03

已知二叉树的后序和中序,求它的先序:

后序:dgebfca

中序:dbegafc

 

我们可以得到树如下:
                 a
               /    /
             b       c
           / /       /
         d   e    f
                /
                 g

 

思路: 二叉树的后续遍历为: 左右中,所以根节点肯定在

 

 

#include <iostream>
using namespace std;

void GetTreeOrder(char bOrder[], int bs, int be,
                  char cOrder[], int cs, int ce)
{
    //if end < begin, we return.
    if(be<bs || ce<cs)
        return;

    //Get the root data of the current recursion.
    char pNewRoot = bOrder[be];

    //1. Output the root node by the define of font order.
    cout<<pNewRoot;

    //if there is only one node, we output it immediately.
    if(be==bs || ce==cs)
        return;

    //here we find the root node in the center order array.
    //find i in cOrder[0------cs-------ce------sumEnd]
    int i = cs;
    for (; i<=ce; i++)
    {
        if(cOrder[i] == pNewRoot)
            break;
    }

    //here we have found i.
    //cOrder: 0------cs----i----ce------sumEnd
    //==>      left part : [cs----i-1]
    //          right part: [i+1----ce]
    //bOrder: 0------bs----x----be------sumEnd
    //&&&     x-bs = i-cs; (left)
    //          be-1-x = ce-i; (right)
    //==>      left part    : [bs----x-1]        ==> [bs----bs+i-cs-1]
    //          right part: [x+1----(be-1)]    ==> [be-ce+i----be-1]

    //2. Out the left node by the define of font order.
    GetTreeOrder(bOrder, bs, bs+i-cs-1, cOrder, cs, i-1);
   
    //3. Output the right node by the define of font order.
    GetTreeOrder(bOrder, be-ce+i, be-1, cOrder, i+1, ce);

}

int main(int argc, char* argv[])
{
    char BackOrder[] = {'d','g','e','b','f','c','a'};
    char CenterOrder[] = {'d','b','e','g','a','f','c'};

    //font order is: abdegcf
    GetTreeOrder(BackOrder, 0, 6, CenterOrder, 0, 6);
    cout<<endl;

    return 0;
}

原创粉丝点击