public class 前序遍历和中序遍历构造二叉树 {
/**
* Definition of TreeNode:
* public class TreeNode {
* public int val;
* public TreeNode left, right;
* public TreeNode(int val) {
* this.val = val;
* this.left = this.right = null;
* }
* }
*/
public static class TreeNode {
public int val;
public TreeNode left, right;
public TreeNode(int val) {
this.val = val;
this.left = this.right = null;
}
}
public static class Solution {
/**
*@param preorder : A list of integers that preorder traversal of a tree
*@param inorder : A list of integers that inorder traversal of a tree
*@return : Root of a tree
*/
public static TreeNode buildTree(int[] preorder, int[] inorder){
if(preorder == null || inorder == null || preorder.length == 0 || inorder.length == 0)
return null;
return buildTree(preorder,inorder,0,preorder.length-1,0,inorder.length-1);
}
public static TreeNode buildTree(int[] preorder, int[] inorder,int pfrom ,int pto,int inbegin, int inend) {
// write your code here
if(pfrom > pto || inbegin > inend || inend >= inorder.length || pto>=preorder.length || pfrom < 0 || inbegin < 0) return null;
System.out.println("pfrom" + pfrom + "pto" + pto + "inbeign" + inbegin + "inend" + inend);
/**
* 根节点元素肯定是preorder[pfrom];
* preorder的第一个节点;
*/
int rootdata = preorder[pfrom];
TreeNode root = new TreeNode (rootdata);
/**
* 根据根节点元素查找到根节点在inorder中的位置;
* 分成left和right两部分;
*/
int rootpos = findRootPosition(inorder,inbegin,inend,rootdata);
/**
* 左边树的长度 rootpos - inbegin;
* 右边树的长度 inend - rootpos;
*/
int leftlen = rootpos - inbegin;//左边长度
int rightlen = inend - rootpos;//右边长度
/**
* 左边树的preorder从 pfrom + 1 到 pfrom+leftlen;
* 左边树的inorder从inbegin到 rootpos - 1;
*
* 右边树的preorder从 pto-rightlen到pto;注意(pto-rightlen+1)到pto
* 右边树的inorder从rootpos+1 到inend;
*/
TreeNode left = buildTree(preorder,inorder,pfrom+1,pfrom+leftlen,inbegin,rootpos-1);
TreeNode right = buildTree(preorder,inorder,pto-rightlen+1,pto,rootpos+1,inend);
root.left = left;
root.right = right;
return root;
}
public static int findRootPosition(int inorder[],int begin, int end ,int root){
for(int i=begin;i<=end;i++)
if(inorder[i] == root)
return i;
return -1;//理论上都可以找到;找不到才返回-1
}
public static void main(String[] args) {
int[] preorder = new int []{1,2};
int[] inorder = new int[]{1,2};
Solution.buildTree(preorder, inorder);
}
}
}