字符串转二叉树
| 56 | |
| 57 | // 字符串转二叉树 |
| 58 | TreeNode* stringToTreeNode(string input) { |
| 59 | trimLeftTrailingSpaces(input); |
| 60 | trimRightTrailingSpaces(input); |
| 61 | input = input.substr(1, input.length() - 2); |
| 62 | if (!input.size()) { |
| 63 | return nullptr; |
| 64 | } |
| 65 | |
| 66 | string item; |
| 67 | stringstream ss; |
| 68 | ss.str(input); |
| 69 | |
| 70 | // 输入是层序遍历形式 [2,1,3,null,4,null,7] |
| 71 | getline(ss, item, ','); |
| 72 | TreeNode* root = new TreeNode(stoi(item)); |
| 73 | queue<TreeNode*> nodeQueue; |
| 74 | nodeQueue.push(root); |
| 75 | |
| 76 | while (true) { |
| 77 | TreeNode* node = nodeQueue.front(); |
| 78 | nodeQueue.pop(); |
| 79 | |
| 80 | if (!getline(ss, item, ',')) { |
| 81 | break; |
| 82 | } |
| 83 | |
| 84 | trimLeftTrailingSpaces(item); |
| 85 | if (item != "null") { |
| 86 | int leftNumber = stoi(item); |
| 87 | node->left = new TreeNode(leftNumber); |
| 88 | nodeQueue.push(node->left); |
| 89 | } |
| 90 | |
| 91 | if (!getline(ss, item, ',')) { |
| 92 | break; |
| 93 | } |
| 94 | |
| 95 | trimLeftTrailingSpaces(item); |
| 96 | if (item != "null") { |
| 97 | int rightNumber = stoi(item); |
| 98 | node->right = new TreeNode(rightNumber); |
| 99 | nodeQueue.push(node->right); |
| 100 | } |
| 101 | } |
| 102 | return root; |
| 103 | } |
| 104 | |
| 105 | |
| 106 | // 二叉树层序遍历形式输出 |
no test coverage detected