105. Construct Binary Tree from Preorder and Inorder Traversal
For example, given:
preorder = [3,9,20,15,7]
inorder = [9,3,15,20,7]
Return the following binary tree:
3
/ \
9 20
/ \
15 7
画了一个复杂点的二叉树来剖析本题的递归,注意尾递归不在搜索范围内,只是用来确定边界,边界一定要考虑清除!
class Solution {
public:
TreeNode *buildTree(vector<int> &preorder, vector<int> &inorder) {
return buildTree(preorder.data(), inorder.data(), inorder.size());
}
private:
TreeNode *buildTree(int *preorder, int *inorder, int size) {
if (NULL == preorder || NULL == inorder || size <= 0) return NULL;
TreeNode *root = new TreeNode(preorder[0]);
if (size == 1) //recursion terminate, trace back
return root;
int rootIndex = 0; //search the root index in inorder
for (; rootIndex < size; rootIndex++)
if (inorder[rootIndex] == root->val) break;
root->left = buildTree(&preorder[1], inorder, rootIndex);
root->right = buildTree(&preorder[rootIndex + 1], &inorder[rootIndex + 1], size - rootIndex - 1);
return root;
}
};
106. Construct Binary Tree from Inorder and Postorder Traversal
given
inorder = [9,3,15,20,7]
postorder = [9,15,7,20,3]
Return the following binary tree:
3
/ \
9 20
/ \
15 7
同样以上面的图为例来说明:
class Solution {
public:
TreeNode* buildTree(vector<int>& inorder, vector<int>& postorder) {
return buildTree(postorder.data(), inorder.data(), inorder.size());
}
private:
TreeNode *buildTree(int *postorder, int *inorder, int size) {
if (NULL == postorder || NULL == inorder || size <= 0) return NULL;
TreeNode *root = new TreeNode(postorder[size-1]);
if (size == 1) //recursion terminate, trace back
return root;
int rootIndex = 0; //search the root index in inorder
for (; rootIndex < size; rootIndex++)
if (inorder[rootIndex] == root->val) break;
root->left = buildTree(&postorder[0], inorder, rootIndex);
root->right = buildTree(&postorder[rootIndex], &inorder[rootIndex + 1], size - rootIndex - 1);
return root;
}
};