• 字符串转二叉树 leetcode C++ 实现


    struct TreeNode {
        int val;
        TreeNode* left;
        TreeNode* right;
    
        explicit TreeNode(int x) : val(x), left(nullptr), right(nullptr) {}
    };
    
    
    void trimLeftTrailingSpaces(string &input) {
        input.erase(input.begin(), find_if(input.begin(), input.end(), [](int ch) {
            return !isspace(ch);
        }));
    }
    
    void trimRightTrailingSpaces(string &input) {
        input.erase(find_if(input.rbegin(), input.rend(), [](int ch) {
            return !isspace(ch);
        }).base(), input.end());
    }
    
    TreeNode* stringToTreeNode(string input) {
        trimLeftTrailingSpaces(input);
        trimRightTrailingSpaces(input);
        input = input.substr(1, input.length() - 2);
        if (input.empty()) {
            return nullptr;
        }
    
        string item;
        stringstream ss;
        ss.str(input);
    
        getline(ss, item, ',');
        auto root = new TreeNode(stoi(item));
        queue<TreeNode*> nodeQueue;
        nodeQueue.push(root);
    
        while (true) {
            TreeNode* node = nodeQueue.front();
            nodeQueue.pop();
    
            if (!getline(ss, item, ',')) {
                break;
            }
    
            trimLeftTrailingSpaces(item);
            if (item != "null") {
                int leftNumber = stoi(item);
                node->left = new TreeNode(leftNumber);
                nodeQueue.push(node->left);
            }
    
            if (!getline(ss, item, ',')) {
                break;
            }
    
            trimLeftTrailingSpaces(item);
            if (item != "null") {
                int rightNumber = stoi(item);
                node->right = new TreeNode(rightNumber);
                nodeQueue.push(node->right);
            }
        }
        return root;
    }
    
    
    void pre_order(TreeNode* root){
        if(root == nullptr) return;
        cout << root->val << ", ";
        pre_order(root->left);
        pre_order(root->right);
    }
    
  • 相关阅读:
    返回三级联动的JSON数据
    返回三级联动的JSON数据
    python3访问map
    第十八讲、中介者模式
    第十七讲、命令模式
    第十六讲、模板方法模式
    第十五讲、组合模式
    第十四讲、享元模式
    第十三讲、装饰器模式
    第十二讲、桥接模式
  • 原文地址:https://www.cnblogs.com/theodoric008/p/9537607.html
Copyright © 2020-2023  润新知