题目要求:
Given preorder and inorder traversal of a tree, construct the binary tree.
通过先序遍历和中序遍历构造二叉树
思路:先序遍历的第一个结点在中序遍历中找到位置i,然后在先序遍历的位置i左边是左子树,先序遍历的位置i右边是右子树,然后递归的构造左右子树
/**
* Definition for a binary tree node.
* public class TreeNode {
* int val;
* TreeNode left;
* TreeNode right;
* TreeNode(int x) { val = x; }
* }
*/
public class Solution {
public TreeNode buildTree(int[] preorder, int[] inorder) {
if(preorder==null||inorder==null||preorder.length==0||inorder.length==0)
{
return null;
}
return buildWithPreIn(preorder,inorder,0,0,inorder.length-1);
}
//根据前序和中序构造二叉树
public TreeNode buildWithPreIn(int[] preorder,int[] inorder,int prestart,int instart,int inend)
{
TreeNode root = null;
for(int i =instart;i<=inend;i++)
{
if(preorder[prestart]==inorder[i])
{
root=new TreeNode(preorder[prestart]);
root.left=buildWithPreIn(preorder,inorder,prestart+1,instart,i-1);
root.right = buildWithPreIn(preorder,inorder,prestart+1+i-instart,i+1,inend);
break;
}
}
return root;
}
}