105. Construct Binary Tree from Preorder and Inorder Traversal
题目:给定一个树的preOrder 和 inOrder 表达,返回这个树
思路:preOrder的第一个数字就是root,然后去inOrder的数组里找root的位置,这个位置的左边为左子树,右边为右子树,然后递归即可
class Solution {
public:
TreeNode* buildTree(vector<int>& preorder, vector<int>& inorder) {
return helper(preorder, 0, preorder.size()-1, inorder, 0, inorder.size()-1);
}
TreeNode* helper(vector<int>& preorder, int pS, int pE, vector<int>& inorder, int iS, int iE)
{
if(preorder.size() != inorder.size())
{
cout<<":dfjaksdfjak"<<endl;
return NULL;
}
if(pS > pE || iS > iE) return NULL;
if(pS == pE || iS == iE)
{
return new TreeNode(preorder[pS]);
}
int rootVal = preorder[pS];
//cout<<"root->va: "<<rootVal;
TreeNode* root = new TreeNode(rootVal);
int i = 0;
for(i = iS; i <= iE; i++)
{
if(inorder[i] == rootVal) break;
}
int length = i - iS;
//cout<<" length of left subtree is: "<<length<<endl;
root->left = helper(preorder, pS+1, pS+length, inorder, iS, i-1);
root->right = helper(preorder, pS+length+1, pE, inorder, i+1, iE);
return root;
}
};
106. Construct Binary Tree from Inorder and Postorder Traversal
题目:给定一个树的inOrder 和 postOrder 表达,返回这个树
思路:和105基本相同,postOrder的最后一个数为root,然后去inOrder的数组里找root的位置,这个位置的左边为左子树,右边为右子树,然后递归即可
class Solution {
public:
TreeNode* buildTree(vector<int>& inorder, vector<int>& postorder) {
return helper(postorder, 0, postorder.size()-1, inorder, 0, inorder.size()-1);
}
TreeNode* helper(vector<int>& postorder, int pS, int pE, vector<int>& inorder, int iS, int iE)
{
if(postorder.size() != inorder.size())
{
cout<<":dfjaksdfjak"<<endl;
return NULL;
}
if(pS > pE || iS > iE) return NULL;
if(pS == pE || iS == iE)
{
return new TreeNode(postorder[pS]);
}
int rootVal = postorder[pE];
//cout<<"root->va: "<<rootVal;
TreeNode* root = new TreeNode(rootVal);
int i = 0;
for(i = iS; i <= iE; i++)
{
if(inorder[i] == rootVal) break;
}
int length = i - iS;
//cout<<" length of left subtree is: "<<length<<endl;
root->left = helper(postorder, pS, pS+length-1, inorder, iS, i-1);
root->right = helper(postorder, pS+length, pE-1, inorder, i+1, iE);
return root;
}
};