给定两个整数数组 preorder
和 inorder
,其中 preorder
是二叉树的先序遍历 , inorder
是同一棵树的中序遍历,请构造二叉树并返回其根节点。
示例 1:
输入: preorder = [3,9,20,15,7], inorder = [9,3,15,20,7]
输出: [3,9,20,null,null,15,7]
示例 2:
输入: preorder = [-1], inorder = [-1]
输出: [-1]
代码:
/**
* Definition for a binary tree node.
* struct TreeNode {
* int val;
* struct TreeNode *left;
* struct TreeNode *right;
* };
*/
struct TreeNode* buildTree(int* preorder, int preorderSize, int* inorder, int inorderSize) {
if(preorderSize<=0||inorderSize<=0) return NULL;
struct TreeNode *root=(struct TreeNode*)malloc(sizeof(struct TreeNode));
int index;
root->val=preorder[0];
for(index=0;index<inorderSize;index++){
if(inorder[index]==preorder[0]){
break;
}
}
root->left=buildTree(preorder+1,index,inorder,index);
root->right=buildTree(preorder+1+index,preorderSize-1-index,inorder+1+index,inorderSize - index - 1);
return root;
}