105 Construct Binary Tree from Preorder and Inorder Traversal 从前序与中序遍历序列构造二叉树

时间:2023-03-09 13:24:25
105 Construct Binary Tree from Preorder and Inorder Traversal 从前序与中序遍历序列构造二叉树

给定一棵树的前序遍历与中序遍历,依据此构造二叉树。
注意:
你可以假设树中没有重复的元素。
例如,给出
前序遍历 = [3,9,20,15,7]
中序遍历 = [9,3,15,20,7]
返回如下的二叉树:
    3
   / \
  9  20
    /  \
   15   7
详见:https://leetcode.com/problems/construct-binary-tree-from-preorder-and-inorder-traversal/description/

Java实现:

/**
* 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[] pre, int[] in) {
if(pre==null||pre.length==0||in==null||in.length==0||pre.length!=in.length){
return null;
}
return reConstructBinaryTree(pre,0,pre.length-1,in,0,in.length-1);
}
private TreeNode reConstructBinaryTree(int[] pre,int startPre,int endPre,int[] in,int startIn,int endIn){
if(startPre>endPre||startIn>endIn){
return null;
}
TreeNode tree=new TreeNode(pre[startPre]);
for(int i=startIn;i<=endIn;++i){
if(in[i]==pre[startPre]){
tree.left=reConstructBinaryTree(pre,startPre+1,startPre+i-startIn,in,startIn,i-1);
tree.right=reConstructBinaryTree(pre,startPre+i-startIn+1,endPre,in,i+1,endIn);
}
}
return tree;
}
}