LEETCODE106:从中序与后序遍历序列构造二叉树
1.题目:
根据一棵树的前序遍历与中序遍历构造二叉树。
注意:
你可以假设树中没有重复的元素。
例如,给出
前序遍历 preorder = [3,9,20,15,7]
中序遍历 inorder = [9,3,15,20,7]
返回如下的二叉树:
3
/ \
9 20
/ \
15 7
2.代码:
/**
* Definition for a binary tree node.
* struct TreeNode {
* int val;
* struct TreeNode *left;
* struct TreeNode *right;
* };
*/
/*
思路:
因为在递归中子串在序列中间,需要标记位置:preorder:[pre_start,pre_end],inorder:[in_start,in_end]
通过preorder知道root->在inorder中找出index_root
->index_root-in_start得到left长度
->通过left长度,找出preorder与inorder中left以及right的开始结束位置;
->分别对left、right进行调用,返回root
--------------------------------------------------------------------------------------
preorder:
[root ,left ,right ];
[pre_start ,(pre_start+1,pre_start+len_left) ,(pre_start+len_left+1,pre_end)];
--------------------------------------------------------------------------------------
inorder :
[left ,root ,right ];
[(in_start,in_start+len_left-1) ,in_start+len_left ,(in_start+len_left+1,in_end)];
--------------------------------------------------------------------------------------
*/
typedef struct TreeNode* Tree;
Tree getTree(int* preorder,int pre_start,int pre_end,int *inorder,int in_start,int in_end){
if(pre_start>pre_end||in_start>in_end)
return NULL;
int i=in_start;
while(inorder[i]!=preorder[pre_start]&&i<=in_end)
i++;
int len_left=i-in_start;
Tree left=getTree(preorder,pre_start+1,pre_start+len_left,inorder,in_start,in_start+len_left-1);
Tree right=getTree(preorder,pre_start+len_left+1,pre_end,inorder,i+1,in_end);
Tree root=malloc(sizeof(struct TreeNode));
root->val=preorder[pre_start];
root->left=left;
root->right=right;
return root;
}
struct TreeNode* buildTree(int* preorder, int preorderSize, int* inorder, int inorderSize){
Tree r=getTree(preorder,0,preorderSize-1,inorder,0,inorderSize-1);
return r;
}
3.知识点:
递归