二叉树.md 1.3 KB

构建二叉树

5 2 3 4 5 -1 -1 -1 -1

#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]

#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;
}