微信公众号搜"智元新知"关注
微信扫一扫可直接关注哦!

从 C 中的字符串构建一棵树在二叉树中定义

如何解决从 C 中的字符串构建一棵树在二叉树中定义

我在 C 中构建树时遇到问题。我尝试使用堆栈来处理嵌套括号,但是我构建的树是错误的。我发现堆栈指针有问题,太难了,我无法修复错误

树是这样构建的:

enter image description here

Fatal error encountered attempting to read the resultset.

解决方法

在我的 C++ 实现中,我在这里使用了两个堆栈,尽管空间补偿仍然是 O(N)。

#include<bits/stdc++.h>
using namespace std;

struct node {
    char data;
    struct node* FirstChild;
    struct node* NextSibling;
    node(char data_) {
        data = data_;
        FirstChild = nullptr;
        NextSibling = nullptr;
    }
};

node *root = nullptr;

node *make_node(char data) {
    node *n = new node(data);
    
    if(root == nullptr) {
        root = n;
        //cout<<"rt "<<n->data<<endl;
    }
    return n;
}


void print_family(node* b,int i) {
    int cnt;
    if (b) {
        for (cnt = 1; cnt < i; cnt++)
            cout << " ";
        cout << b->data << endl;
        print_family(b->FirstChild,i + 1);
        print_family(b->NextSibling,i);
    }
}

void make_tree(string s) {

    stack<node*> st;
    stack<node*> parent;


    for(int i = 0; i < s.length(); i++) {
        if(s[i+1] == '(') {
            node *n = make_node(s[i]);
            st.push(n);
            parent.push(n);
            
        else if(s[i] == ')') {

            vector<node*> pipe;
            
            while(1) {
                if(st.top()->data == parent.top()->data){
                    break;
                }
                pipe.push_back(st.top());
                st.pop();

            }


            if(pipe.size() <= 2) {
                parent.top()->FirstChild = pipe[0];
                if(pipe.size() == 2){
                    parent.top()->FirstChild->NextSibling = pipe[1];
                }
            }

            parent.pop();
        }
        else{
            if(s[i] != ',' and s[i] != '(')
                st.push(make_node(s[i]));
        }
    }
}



int main() {
    string s = "a(b(d,e),c(g(s),f))";

    make_tree(s);


    print_family(root,5);

}

输出 enter image description here

版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。