#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;
}
};
利用前序和中序遍历重建二叉树
最新推荐文章于 2023-07-20 11:04:27 发布