一、题目
根据一棵树的前序遍历与中序遍历构造二叉树。
注意:你可以假设树中没有重复的元素。
例如,给出
前序遍历 preorder = [3,9,20,15,7]
中序遍历 inorder = [9,3,15,20,7]
返回如下的二叉树:
二、思路及代码实现
详细过程参考二叉搜索树,链接:
https://blog.csdn.net/weixin_45594025/article/details/104477793
代码实现:
/**
* Definition for a binary tree node.
* public class TreeNode {
* int val;
* TreeNode left;
* TreeNode right;
* TreeNode(int x) { val = x; }
* }
*/
class Solution {
public TreeNode buildTree(int[] preorder, int[] inorder) {
if(preorder.length == 0){
return null;
}
TreeNode root = buildTree(preorder, inorder, 0, preorder.length - 1, 0, inorder.length - 1);
return root;
}
public TreeNode buildTree(int[] preorder, int[] inorder, int preS, int preE, int inS, int inE) {
TreeNode root = new TreeNode(preorder[preS]);
if(preS == preE){
return root;
}
int index = 0;// index of root
for(int i = 0; i < inorder.length; i++){
if(inorder[i] == preorder[preS])
index = i;
}
int leftLength = index - inS;
if(leftLength > 0){
root.left = buildTree(preorder, inorder, preS + 1, preS + leftLength, inS, index - 1);
}
int rightLength = inE - index;
if(rightLength > 0){
root.right = buildTree(preorder, inorder, preS + leftLength + 1, preE, index + 1, inE);
}
return root;
}
}