题意:给出一个二叉树的先序遍历和中序遍历的结果,请创建这样的一颗二叉树。(即已知DLR和LDR,确定唯一的二叉树)
刚开始拿到这个题无从下手,想了很长一段时间后,打算先写出要创建二叉树的列表list(根据已知答案,按照先序遍历的方法),将list对比已知的DLR和LDR列表,找到了规律,result列表相比于DLR列表,中间多插入了一些nullptr,而在哪些地方插入nullptr可根据DLR和LDR列表的规律,用到了stack库这种数据结构,解答过程如下:
#include<iostream>
#include<vector>
#include<stack>
#define NUL 100000
using namespace std;
// Definition for a binary tree node.
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) {}
};
class Solution {
public:
TreeNode* buildTree(vector<int>& preorder, vector<int>& inorder) {
if (preorder.empty() || inorder.empty())
return nullptr;
stack<int> sta;
vector<int> list;
int j = 0, index = 0;
//生成list列表,用于先序创建二叉树
for (int i = 0; i < preorder.size(); i++)
{
if (j < inorder.size()){
list.push_back(preorder[i]);
if (preorder[i] != inorder[j])
{
sta.push(preorder[i]);
}
else
{
list.push_back(NUL);
j++;
while (!sta.empty() && j < inorder.size() && sta.top() == inorder[j])
{
list.push_back(NUL);
j++;
sta.pop();
}
}
}
}
TreeNode* root;
CreateBit(root, list, index);
return root;
}
void CreateBit(TreeNode* &, vector<int>&, int&);
};
//传入指针的引用,效果上相当于传入二级指针,可以在调用函数中直接new开辟空间(这个地方需要好好理解)
void Solution::CreateBit(TreeNode* & ptr, vector<int>& list, int& index){
if (index < list.size() && list[index] != NUL)
{
ptr = new TreeNode(list[index]); //不用担心ptr指向的新的空间,因为这里是指针的引用,相当于传入TreeNode** ptr,实现
//*ptr=new TreeNode(list[index])的赋值
CreateBit(ptr->left, list, ++index);
CreateBit(ptr->right, list, ++index);
}
}