c ++ binary tree traversal

Title Description

Each internal node binary tree is at most two child nodes, and two child nodes ordered tree. FIG binary tree is as follows:

Binary Tree

For a binary tree traversal There are three basic ways:
1. preorder traversal: first visit the root, then preorder traversal left subtree, right subtree final order traversal before;

2. preorder: first preorder left subtree, then visit the root node, the last preorder right subtree;

3. postorder: preorder traversal has left subtree, then the right subtree traversal sequence after the last root access.

For the figure, the result is preorder traversal ABDEHCFGI. In order traversal result DBEHAFCIG, postorder traversal result is DHEBFIGCA.

We will now be given of the preamble and binary tree traversal sequence, output a corresponding post-order traversal.

Entry

Before the first line of a preorder traversal results

The second row of results preorder

All capital letters, and the node identifier will not be repeated, at most 100 nodes.

Export

After the result output preorder

Sample input

ABDEHCFGI
DBEHAFCIG

Sample Output

DHEBFIGCA

Source Code

#include <iostream>
#include <string.h>
using namespace std;
char a[110],b[110];//a[]是前序遍历的结果  b[]是中序遍历的结果
void dfs(int f1,int e1,int f2,int e2)
{
    if(f1>e1) return;//如果找不到子节点就退出(起点大于终点)
    int rt=f1;//rt是根节点
    int p = 0;
    //计算出左子树或者右子树的下一层根节点
    for(int i=f2;i<=e2;i++)
        if(b[i]==a[rt])//如果找到了顶点
        {
            p=i;//p代表顶点在b[]里面的位置  即b[p]
            break;
        }
    int ls=p-1-f2+1;//ls表示长度
    //int rs=e2-(p+1)+1;
    dfs(f1+1,f1+1+ls-1,f2,p-1);//递归处理左子树
    //f1+1:a[]的左子树的起点  f1+1+ls-1:a[]的左子树的终点
    //f2:b[]的左子树的起点  p-1:b[]的左子树的终点
    dfs(f1+1+ls-1+1,e1,p+1,e2);//递归处理右子树
    //f1+1+ls-1+1:a[]的右子树的起点  e1:a[]的右子树的终点
    //p+1:b[]的右子树的起点  e2:b[]的右子树的终点
    printf("%c",a[rt]);//如果这是一个叶节点(既没有左子树,也没有右子树),就输出它
}
int main()
{
    //scanf("%s%s",a,b);
    cin >> a >> b;
    dfs(0,int(strlen(a))-1,0,int(strlen(b))-1);//起点
    cout << endl;
    return 0;
}
/*
 思路总结:
 先以a为顶点,递归寻找a的左子树  如果a有左子树,先判断下一个节点b是否为顶点 (判断b是否为顶点:判断b是否有左右子树)
 找到b的左子树的下一个节点d 再继续判断d是否有左右子树  如果没有,d为叶节点
 在找到b的右子树的下一个节点e 判断e的左右子树 如果有,继续判断下一个节点h是否有左右子树 直到找到h叶子节点
 在找到a的右子树的下一个节点c 判断c的左右子树 如果有,继续判断下一个节点 f和g 是否有左右子树 直到找到i叶子节点
 每次找到叶子节点就输出
*/

Guess you like

Origin www.cnblogs.com/LJA001162/p/11334924.html