Given preorder and inorder (Inorder and Postorder) traversal of a tree, construct the binary tree.
Note:
You may assume that duplicates do not exist in the tree.
前序和后序的特点是根结点要么在最前面、要么在最后面。已知根结点后,以根结点为界将中序遍历的结果分成两段,然后递归即可还原二叉树。有两点需要注意:首先二叉树中不能有重复的结点;其次,已知前序和后序遍历结果是无法还原二叉树的。
已知前序和中序,构建二叉树:
/**
* Definition for a binary tree node.
* 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,int from1,int to1,
vector<int>& inorder,int from2,int to2)
{
if(from1>to1)
return NULL;
int i=from2;
for(;i<=to2;++i)
{
if(inorder[i]==preorder[from1])
break;
}
TreeNode* root=new TreeNode(inorder[i]);
root->left=buildTree(preorder,from1+1,from1+i-from2,inorder,from2,i-1);
root->right=buildTree(preorder,from1+i-from2+1,to1,inorder,i+1,to2);
return root;
}
TreeNode* buildTree(vector<int>& preorder, vector<int>& inorder) {
return buildTree(preorder,0,preorder.size()-1,inorder,0,inorder.size()-1);
}
};
已知中序和后序,构建二叉树:
/**
* Definition for a binary tree node.
* 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,int from1,int to1,
vector<int>& postorder,int from2,int to2)
{
if(from1>to1)
return NULL;
// if(from1==to1)
// {
// TreeNode* tmp=new TreeNode(inorder[from1]);
// return tmp;
// }
int i=from1;
for(;i<=to1;++i)
{
if(inorder[i]==postorder[to2])
break;
}
TreeNode* root=new TreeNode(inorder[i]);
root->left=buildTree(inorder,from1,i-1,postorder,from2,from2+i-from1-1);
root->right=buildTree(inorder,i+1,to1,postorder,from2+i-from1,to2-1);
return root;
}
TreeNode* buildTree(vector<int>& inorder, vector<int>& postorder) {
return buildTree(inorder,0,inorder.size()-1,postorder,0,postorder.size()-1);
}
};