标签:ems tree solution val ret 位置 http 后序 str
/**
* 输入某二叉树的前序遍历和中序遍历的结果,请重建该二叉树。
* 假设输入的前序遍历和中序遍历的结果中都不含重复的数字。
**/
#include<iostream>
#include<cstring>
#include<string>
#include<algorithm>
#include<cstdio>
#include<queue>
#include<vector>
using namespace std;
// Definition for a binary tree node.
struct TreeNode {
int val;
TreeNode *left;
TreeNode *right;
TreeNode(int x) : val(x), left(NULL), right(NULL) {}
};
/**
* [3,9,20,15,7]
* [9,3,15,20,7]
3
/ 9 20
/ 15 7
**/
class Solution {
private:
int sum=0;//
int l,r;
public:
TreeNode* buildTree(vector<int>& preorder, vector<int>& inorder) {
int length=preorder.size();
int startpre=0,startin=0,endpre=length-1,endin=length-1;
return buildTree(preorder,inorder,startpre,endpre,startin,endin);
}
//每次根据当前子树的前序以及后序遍历的位置来重建左右子树
TreeNode* buildTree(vector<int>& preorder,vector<int>& inorder,int startpre,int endpre,int startin,int endin){
if(startpre>endpre||startin>endin)
return NULL;
int discrepancy=0;//表示从中序遍历中找到的分割左右子树的位置
while(inorder[startin+discrepancy]!=preorder[startpre]){
discrepancy++;
}
TreeNode* node=new TreeNode(preorder[startpre]);
node->left=buildTree(preorder,inorder,startpre+1,startpre+discrepancy,startin,startin+discrepancy-1);
node->right=buildTree(preorder,inorder,startpre+discrepancy+1,endpre,startin+discrepancy+1,endin);
return node;
}
};
int main(){
TreeNode* t1=new TreeNode(10);
TreeNode* t2=new TreeNode(5);
TreeNode* t3=new TreeNode(15);
TreeNode* t4=new TreeNode(3);
TreeNode* t5=new TreeNode(7);
TreeNode* t6=new TreeNode(18);
t2->left=t4;t2->right=t5;
t3->left=t6;
t1->left=t2;t1->right=t3;
Solution solution;
system("pause");
return 0;
}
标签:ems tree solution val ret 位置 http 后序 str
原文地址:https://www.cnblogs.com/GarrettWale/p/12354283.html