给出中序遍历:[1,2,3]和前序遍历:[2,1,3]. 返回如下的树:
2
/ \
1 3
根据前序遍历的特点, 知前序序列(PreSequence)的首个元素(PreSequence[0])为二叉树的根(root), 然后在中序序列(InSequence)中查找此根(root), 根据中序遍历特点, 知在查找到的根(root) 前边的序列为根的左子树的中序遍历序列, 后边的序列为根的右子树的中序遍历序列。 设在中序遍历序列(InSequence)根前边有left个元素. 则在前序序列(PreSequence)中, 紧跟着根(root)的left个元素序列(即PreSequence[1…left]) 为根的左子树的前序遍历序列, 在后边的为根的右子树的前序遍历序列.而构造左子树问题其实跟构造整个二叉树问题一样,只是此时前序序列为PreSequence[1…left]), 中序序列为InSequence[0…left-1], 分别为原序列的子串, 构造右子树。
具有明显的递归特性
/**
* 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
*/
public TreeNode buildTree(int[] preorder, int[] inorder) {
// write your code here
//检查参数
if(preorder.length == 0 || inorder.length == 0||
preorder.length != inorder.length)
return null;
//建立根
TreeNode root = build(preorder,0,inorder,inorder.length - 1,inorder.length);
return root;
}
//切分序列,递归解决,理解简单,效率低
public TreeNode build(int[] preorder, int start, int[] inorder, int end,int length)
{
//检查参数
if(preorder.length == 0 || inorder.length == 0 || length <= 0)
return null;
TreeNode rootNode = new TreeNode(preorder[start]);
//仅有根节点
if(length == 1)
return rootNode;
int i = 0;
//找出序列中的分割点,从尾部开始查找
while(i < length)
{
if(rootNode.val == inorder[end - i])//根节点在end - i处出现
break; //end - i - 1为左序列结束
i ++; //
}
//递归调用
//左序列
rootNode.left = build( preorder,
start + 1, //左树根
inorder,
end - i -1, //左序列结束
length - i - 1); //序列长度
//右序列
rootNode.right = build( preorder,
start + length - i, //右树根,左树根位置+左序列长度
inorder,
end, //右序列结束
i); //序列长度
return rootNode;
}
}