Last active
August 4, 2021 10:10
-
-
Save Molin-L/860aab42b2c616995ffa4e801070825b to your computer and use it in GitHub Desktop.
Leetcode Binary Tree Generator
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
#include <iostream> | |
#include <vector> | |
#include <sstream> | |
#include <queue> | |
using namespace std; | |
/** | |
* @brief Definition of TreeNode | |
*/ | |
struct TreeNode { | |
int val; | |
TreeNode *left; | |
TreeNode *right; | |
TreeNode() : val(0), left(nullptr), right(nullptr) {} | |
TreeNode(int x) : val(x), left(nullptr), right(nullptr) {} | |
TreeNode(int x, TreeNode *left, TreeNode *right) : val(x), left(left), right(right) {} | |
}; | |
/** | |
* @brief Convert raw string input into vector. | |
* | |
* @param[in] raw Raw string input | |
* @return vector<string> | |
*/ | |
vector<string> _raw_reader(string raw) { | |
vector<string> result; | |
istringstream iss(raw); | |
string temp; | |
const char delim = ','; | |
while (getline(iss, temp, delim)) { | |
result.emplace_back(move(temp)); | |
} | |
return result; | |
} | |
TreeNode* new_node(string s) { | |
if (s == "null") { | |
return nullptr; | |
} | |
int num = stoi(s); | |
return new TreeNode(num); | |
} | |
/** | |
* @brief Convert vector into binary tree | |
* | |
* @param[in] nodes vector of nodes' value | |
* @return struct TreeNode* | |
*/ | |
struct TreeNode* _vec2tree(const vector<string> &nodes) { | |
if (nodes.size()==0 || nodes[0] == "null") { | |
return nullptr; | |
} | |
deque<TreeNode*> ptr_queue; | |
TreeNode* root = new_node(nodes[0]); | |
if (nodes.size() == 1) { | |
return root; | |
} | |
TreeNode* cur = root; | |
ptr_queue.push_back(cur); | |
deque<TreeNode*> ptr_temp; | |
int i = 1; | |
while (ptr_queue.size() && i<nodes.size()) { | |
cur = ptr_queue.front(); | |
cur->left = new_node(nodes[i]); | |
ptr_queue.push_back(cur->left); | |
i++; | |
if (i<nodes.size()) { | |
cur->right = new_node(nodes[i]); | |
ptr_queue.push_back(cur->right); | |
} | |
ptr_queue.pop_front(); | |
i++; | |
} | |
return root; | |
} | |
/** | |
* @brief Generate Binary Tree from string. | |
* | |
* @param[in] raw Raw string | |
* @return TreeNode* root | |
*/ | |
TreeNode* generate_BT(string raw) { | |
if (raw[0] == '[') { | |
raw = raw.substr(1, raw.length()-2); | |
} | |
vector<string> vec = _raw_reader(raw); | |
return _vec2tree(vec); | |
} | |
/** | |
* Demo | |
*/ | |
int main() { | |
string raw = "[10,5,-3,3,2,null,11,3,-2,null,1]"; | |
TreeNode* root = generate_BT(raw); | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
实现了Leetcode的字符串转二叉树,以满足本地测试需求。
文件末尾给出了个Demo供参考使用。
This
.cpp
file is for local debugging use.At the end of file, I give an example, which you can refer from.