[二叉樹建樹] 根據前序遍歷構造二叉樹

題目描述

編一個程序,讀入用戶輸入的一串先序遍歷字符串,根據此字符串創建一個二叉樹(以指針方式存儲)。
例如以下的先序遍歷字符串:
ABC##DE#G##F###
其中「#」表示的是空格,空格字符表明空樹。創建起此二叉樹之後,再對二叉樹進行中序遍歷,輸出遍歷結果。html

輸入

輸入包括1行字符串,長度不超過100。node

輸出

可能有多組測試數據,對於每組數據,
輸出將輸入字符串創建二叉樹後中序遍歷的序列,每一個字符後面都有一個空格。
每一個輸出結果佔一行。ios

樣例輸入

a#b#cdef#####a##

樣例輸出

a b f e d c
注:每一個字母后面跟着一個空格。
 
分析:與二叉樹復原進行對比,是兩種不一樣的構建二叉樹的方法。
 
#include <iostream>
#include <cstdio>
#include <cmath>
#include <cstring>
#include <algorithm>
#include <vector>
using namespace std;

string input;

struct node
{
    char data;
    node * lchild,*rchild;
};

void preOrder(node * & root,int & index)
{
    if(index>=input.length())
    {
        return ;
    }
    if(input[index]=='#')
    {
        root=NULL;
        index++;
    }
    else
    {
        root=new node;
        root->data=input[index];
        index++;
        preOrder(root->lchild,index);
        preOrder(root->rchild,index);
        
    }
}

void inOrder(node * root)
{
    if(root==NULL)
    {
        return ;
    }
    inOrder(root->lchild);
    cout<<root->data<<" ";
    inOrder(root->rchild);
}

int main()
{
    while(cin>>input)
    {
        node * root=NULL;
        int index=0;
        preOrder(root,index);
        inOrder(root);
        cout<<endl;
    }
}
相關文章
相關標籤/搜索