package Recursion;
public class BuildTree_105 {
public class TreeNode {
int val;
TreeNode left;
TreeNode right;
TreeNode(int x) {
val = x;
}
}
// 105. Construct Binary Tree from Preorder and Inorder Traversal
public TreeNode buildTree(int[] preorder, int[] inorder) {
return recur(preorder,0,preorder.length-1,inorder,0,inorder.length-1);
}
private TreeNode recur(int[] preorder,int pStart,int pEnd,int[] inorder,int iStart,int iEnd){
// 递归结束条件
while(pStart>pEnd||iStart>iEnd) {
return null;
}
TreeNode treeNode=new TreeNode(preorder[pStart]);
int index=0;
while(inorder[iStart+index]!=preorder[pStart]) {
index++;
}
treeNode.left=recur(preorder,pStart+1,pStart+index,inorder,iStart,iStart+index-1);
treeNode.right=recur(preorder,pStart+index+1,pEnd,inorder,iStart+index+1,iEnd);
return treeNode;
}
}
105. Construct Binary Tree from Preorder and Inorder Traversal
最新推荐文章于 2021-05-26 18:38:00 发布