C/C++建一颗二叉树
在刷题的时候,很多时候给一个数组,需要建一个简单的二叉树
#include<iostream> #include<vector> #include<queue> 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) {} TreeNode(int x, TreeNode *left, TreeNode *right) : val(x), left(left), right(right) {} }; TreeNode* newNode(int data){ TreeNode* node = new TreeNode; node->val = data; node->left = node->right = nullptr; return node; } TreeNode* createTree(vector<int> &nums, int n, int index){ TreeNode* node = nullptr; if (index < n && nums[index] != -1){ node = newNode(nums[index]); node->left = createTree(nums, n, 2*index+1 ); node->right = createTree(nums, n, 2*index+2 ); } return node; } int main(){ vector<int> nums{3,9,20,-1,-1,15,7}; TreeNode* root = createTree(nums, nums.size(), 0); return 0; }