leetcode字符串生成二叉树模板

leetcode字符串生成二叉树模板

code

#include<iostream>
#include<vector>
#include<queue>
#include<string>

using namespace std;

struct TreeNode {
    int val;
    TreeNode* left;
    TreeNode* right;
    TreeNode(int x) : val(x), left(NULL), right(NULL) {}
};

TreeNode* build_tree(vector<string>& v) {
    if (v.empty() || v[0] == "null") return nullptr;
    TreeNode* root = new TreeNode(stoi(v[0])), * cur;
    queue<TreeNode*> q;
    q.push(root);
    int node_num = 0, idx = 0, N = v.size();
    while (!q.empty() && idx < N - 1) {
        node_num = q.size();
        while ((node_num-- > 0) && (idx < N - 1)) {
            cur = q.front(); q.pop();
            if ((++idx < N) && (v[idx] != "null")) {
                cur->left = new TreeNode(stoi(v[idx]));
                q.push(cur->left);
            }
            if ((++idx < N) && (v[idx] != "null")) {
                cur->right = new TreeNode(stoi(v[idx]));
                q.push(cur->right);
            }
        }
    }
    return root;
}

void inorder(TreeNode* root) {
    if (root == nullptr) return;
    inorder(root->left);
    cout << root->val << ' ';
    inorder(root->right);
}

int main() {
    string s;
    vector<string> node_infor;//因数据包含null,因此使用此类型存储节点信息
    cout << "Input node val(leetcode form): ";
    getline(cin, s);
    s.assign(s.begin() + 1, s.end() - 1); //去括号

    int cont = 0;
    for (auto ch = s.begin(); ch != s.end(); ch++) {
        if (*ch != ',') cont++;
        else {
            node_infor.push_back(s.substr(ch - s.begin() - cont, cont));
            cont = 0;
        }
    }//逗号分隔字符串
    if (!s.empty()) {
        node_infor.push_back(s.substr(s.size() - cont, cont));
    }
    TreeNode* root = build_tree(node_infor);
    cout << "Inorder traversal: "; inorder(root);//中序遍历验证

    return 0;
}
  • 1
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

black-hole6

你的鼓励将是我创作的动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值