Explorar o código

新增两个输入输出样例

seamew %!s(int64=2) %!d(string=hai) anos
pai
achega
34881ae5fa
Modificáronse 2 ficheiros con 121 adicións e 0 borrados
  1. 70 0
      算法/输入输出/二叉树.md
  2. 51 0
      算法/输入输出/链表.md

+ 70 - 0
算法/输入输出/二叉树.md

@@ -0,0 +1,70 @@
+## 构建二叉树
+
+5
+2 3
+4 5
+-1 -1
+-1 -1
+
+```cpp
+#include <bits/stdc++.h>
+
+using namespace std;
+
+struct TreeNode {
+    int val;
+    TreeNode *left;
+    TreeNode *right;
+    TreeNode() : val(0), left(nullptr), right(nullptr) {}
+    TreeNode(int x) : val(x), left(nullptr), right(nullptr) {}
+};
+
+int main() {
+    int n;
+    cin >> n;
+    vector<TreeNode*> nodes(n);
+    for (int i = 0; i < n; i++) {
+        nodes[i] = new TreeNode(i);
+    }
+    for (int i = 0; i < n; i++) {
+        int left, right;
+        cin >> left >> right;
+        if (left != -1) nodes[i]->left = nodes[left - 1];
+        if (right != -1) nodes[i]->right = nodes[right - 1];
+    }
+    return 0;
+}
+```
+
+## 构建二叉树
+
+[4,2,7,1,3,6,9]
+
+```cpp
+#include <bits/stdc++.h>
+
+using namespace std;
+
+struct TreeNode {
+    int val;
+    TreeNode *left;
+    TreeNode *right;
+    TreeNode() : val(0), left(nullptr), right(nullptr) {}
+    TreeNode(int x) : val(x), left(nullptr), right(nullptr) {}
+};
+
+void buildTree(TreeNode*& node, vector<int>& nums, int len, int index) {
+    if (index >= len) return;
+    node = new TreeNode(nums[index]);
+    buildTree(node->left, nums, len, 2 * index + 1);
+    buildTree(node->right, nums, len, 2 * index + 2);
+}
+
+int main() {
+    vector<int> nums = {4, 2, 7, 1, 3, 6, 9};
+    TreeNode* root;
+    buildTree(root, nums, nums.size(), 0);
+    return 0;
+}
+```
+

+ 51 - 0
算法/输入输出/链表.md

@@ -0,0 +1,51 @@
+# 输入数组构建链表
+
+```cpp
+#include <bits/stdc++.h>
+
+using namespace std;
+
+struct ListNode {
+    int val;
+    ListNode *next;
+
+    ListNode() : val(0), next(nullptr) {}
+
+    ListNode(int x) : val(x), next(nullptr) {}
+};
+
+ListNode *buildListNode(vector<int> &nums) {
+    ListNode *root = new ListNode();
+    ListNode *cur = root;
+    for (const auto &item: nums) {
+        ListNode *node = new ListNode(item);
+        cur->next = node;
+        cur = node;
+    }
+    return root;
+}
+
+void printListNode(ListNode *root) {
+    ListNode *cur = root->next;
+    while (cur) {
+        cout << cur->val << " ";
+        cur = cur->next;
+    }
+    cout << endl;
+}
+
+int main() {
+    string str;
+    vector<int> nums;
+    string num;
+    cin >> str;
+    stringstream ss(str);
+    while (getline(ss, num, ',')) {
+        nums.push_back(stoi(num));
+    }
+    ListNode *root = buildListNode(nums);
+    printListNode(root);
+    return 0;
+}
+```
+