#pragma once #include<vector> #include<iostream> using namespace std; struct TreeNode { int val; TreeNode *left; TreeNode *right; TreeNode(int x) : val(x), left(NULL), right(NULL) {} }; class Solution { public: TreeNode * reConstructBinaryTree(int pre[], int vin[],int length) {//pre前序数组,vin中序数组,length数组长度 TreeNode*node = new TreeNode(0);//父节点 if (length == 0) { return NULL; } node->val = *pre;//父节点赋值 int root_index = 0; /*找到中序数组中根节点所在位置*/ for (; root_index <length; root_index++) { if (vin[root_index] ==*pre) break; } node->left = reConstructBinaryTree(pre + 1, vin, root_index);//左孩赋值 node->right = reConstructBinaryTree(pre + root_index + 1, vin + root_index + 1, length - root_index - 1);//右孩赋值 //cout << node->val << endl; return node; } };
利用前序和中序遍历重建二叉树
猜你喜欢
转载自blog.csdn.net/m0_37895939/article/details/80184299
今日推荐
周排行