前序遍历 中序遍历树构造二叉树
/**
* 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 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
*/
//找到根节点的位置
private int findPosition(int[] array, int start, int end, int key) {
for (int i = start; i <= end; i++) {
if (array[i] == key) {
return i;
}
}
return -1;
}
private TreeNode myBuildTree(int[] preorder, int preStart, int preEnd, int[] inorder, int inStart, int inEnd) {
if (inStart > inEnd) {
return null;
}
//前序遍历序列的第一个数字就是根结点,创建根结点root
TreeNode root = new TreeNode(preorder[preStart]);
//在中序遍历序列中找到根结点的位置
int position = findPosition(inorder, inStart, inEnd, preorder[preStart]);
//构建左子树
root.left = myBuildTree(preorder, preStart + 1, preStart + (position - inStart), inorder, inStart, position - 1);
//构建右子树
root.right = myBuildTree(preorder, preStart + (position - inStart) + 1, preEnd, inorder, position + 1, inEnd);
return root;
}
public TreeNode buildTree(int[] preorder, int[] inorder) {
if (preorder.length != inorder.length) {//前序遍历序列与中序遍历序列长度不等
return null;
}
return myBuildTree(preorder, 0, preorder.length - 1, inorder, 0, inorder.length - 1);
}
}