美文网首页
根据前序建二叉树

根据前序建二叉树

作者: atok | 来源:发表于2019-02-21 11:00 被阅读0次

题目(清华机试)

编一个程序,读入用户输入的一串先序遍历字符串,根据此字符串建立一个二叉树(以指针方式存储)。 例如如下的先序遍历字符串: ABC##DE#G##F### 其中“#”表示的是空格,空格字符代表空树。建立起此二叉树以后,再对二叉树进行中序遍历,输出遍历结果。

思路

按照前序遍历特点,递归建树

代码

#include<iostream>
#include<string>
using namespace std;

int i;
string str; 

struct node
{
    char val;
    node *left, *right;
    node(char c) : val(c), left(NULL), right(NULL) {}
};

node *createTree()
{
    char c = str[i++];
    if(c == '#') return NULL;
    node *root = new node(c);
    root -> left = createTree();
    root -> right = createTree();
    return root;
}

void inOrder(node *root)
{
    if(!root) return;
    inOrder(root -> left);
    cout << root -> val << " ";
    inOrder(root -> right);
}

int main()
{
    while(cin >> str) {
        i = 0;
        node *root = createTree();
        inOrder(root);
        cout << endl;
    }
    return 0;
}

相关文章

网友评论

      本文标题:根据前序建二叉树

      本文链接:https://www.haomeiwen.com/subject/elfryqtx.html