zoukankan      html  css  js  c++  java
  • 字符串转二叉树 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);
    }
    
  • 相关阅读:
    如何拷贝CMD命令行文本到粘贴板
    Linux 系统时钟(date) 硬件时钟(hwclock)
    Android AIDL自动生成Java文件测试
    Windows Tftpd32 DHCP服务器 使用
    Cmockery macro demo hacking
    Linux setjmp longjmp
    GrepCode
    Windows bat with adb
    点分十进制IP校验、转换,掩码校验
    子网掩码、掩码长度关系
  • 原文地址:https://www.cnblogs.com/theodoric008/p/9537607.html
Copyright © 2011-2022 走看看