题目描述
根据一棵树的前序遍历与中序遍历构造二叉树。
注意:
你可以假设树中没有重复的元素。
样例
例如,给出
前序遍历 preorder = [3,9,20,15,7]
中序遍历 inorder = [9,3,15,20,7]
返回如下的二叉树:
3
/ \
9 20
/ \
15 7
算法1
(递归) O(n^2)
C 代码
/**
* Definition for a binary tree node.
* struct TreeNode {
* int val;
* struct TreeNode *left;
* struct TreeNode *right;
* };
*/
struct TreeNode* dfs(int *pre, int *in, int pl, int pr, int il, int ir, int n)
{
if (pl > pr) {
return NULL;
}
int k = 0;
for (int i = 0; i < n; i ++ ) {
if (in[i] == pre[pl]) {
k = i - il;
}
}
struct TreeNode *root = (struct TreeNode*)malloc(sizeof(struct TreeNode));
memset(root, 0x00, sizeof(struct TreeNode));
root->val = pre[pl];
root->left = dfs(pre, in, pl + 1, pl + k, il, il + k + 1, n);
root->right = dfs(pre, in, pl + k + 1, pr, il + k + 1, ir, n);
return root;
}
struct TreeNode* buildTree(int* preorder, int preorderSize, int* inorder, int inorderSize){
int n = preorderSize;
return dfs(preorder, inorder, 0, preorderSize - 1, 0, inorderSize - 1, n);
}