题目链接:牛客网
给出一棵树的前序遍历和中序遍历,请构造这颗二叉树
注意:
可以假设树中不存在重复的节点
先遍历的第一个数是根节点,中序遍历的根节点左边是左子树,右边是右子树。通过先序遍历遍历找到根结点,通过中序中根结点的位置可以将树划分成两个子树,然后递归的进行调用即可构造好二叉树。
/**
* Definition for binary tree
* struct TreeNode {
* int val;
* TreeNode *left;
* TreeNode *right;
* TreeNode(int x) : val(x), left(NULL), right(NULL) {}
* };
*/
class Solution {
public:
TreeNode *buildTree(vector<int> &preorder, vector<int> &inorder) {
int lenIn = inorder.size();
int lenPre = preorder.size();
return buildTree_Aux(inorder,0,lenIn-1,preorder,0,lenPre-1);
}
TreeNode *buildTree_Aux(vector<int> &inorder,int inB,int inE,
vector<int> &preorder,int prB,int prE) {
if(inB > inE || prB > prE)
return NULL;
//在先序遍历中确定根节点
TreeNode* root = new TreeNode(preorder[prB]);
//在中序遍历中确定左右子树
vector<int>::iterator iter = find(inorder.begin()+inB,inorder.begin()+inE,preorder[prB]);
int index = iter - inorder.begin();
root->left = buildTree_Aux(inorder,inB,index-1,preorder,prB+1,prB+index-inB);
root->right = buildTree_Aux(inorder,index+1,inE,preorder,prB+index-inB+1,prE);
return root;
}
};
题目链接:牛客网
给出一棵树的中序遍历和后序遍历,请构造这颗二叉树
注意:
保证给出的树中不存在重复的节点
后序遍历的最后一个数是根节点,中序遍历的根节点左边是左子树,右边是右子树。通过后序遍历找到根结点,通过中序中根结点的位置可以将树划分成两个子树,然后递归的进行调用即可构造好二叉树。
/**
* Definition for binary tree
* struct TreeNode {
* int val;
* TreeNode *left;
* TreeNode *right;
* TreeNode(int x) : val(x), left(NULL), right(NULL) {}
* };
*/
class Solution {
public:
TreeNode *buildTree(vector<int> &inorder, vector<int> &postorder) {
int lenIn = inorder.size();
int lenPost = postorder.size();
return buildTree_Aux(inorder,0,lenIn-1,postorder,0,lenPost-1);
}
TreeNode *buildTree_Aux(vector<int> &inorder,int inB,int inE,
vector<int> &postorder,int poB,int poE) {
if(inB > inE || poB > poE)
return NULL;
//在后序遍历中确定根节点
TreeNode* root = new TreeNode(postorder[poE];
//在中序遍历中确定左右子树
vector<int>::iterator iter = find(inorder.begin()+inB,inorder.begin()+inE,postorder[poE]);
int index = iter - inorder.begin();
root->left = buildTree_Aux(inorder,inB,index-1,postorder,poB,poB+index-1-inB);
root->right = buildTree_Aux(inorder,index+1,inE,postorder,poB+index-inB,poE-1);
return root;
}
};