问题
Given preorder and inorder traversal of a tree, construct the binary tree.
** Notice
You may assume that duplicates do not exist in the tree.
Have you met this question in a real interview? Yes
ExampleGiven in-order [1,2,3]
and pre-order [2,1,3]
, return a tree:
分析
以这个二叉树为例,前序是1245367,中序是4251637。我们知道前序的第一个一定是根结点。所以先把1找出来,然后在中序里边找到1,那么1左边的一定是1的左子树,1右边的一定是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
return buildTree(preorder,0,preorder.length-1,inorder,0,inorder.length-1);
}
private TreeNode buildTree(int[] preorder,int pleft,int pright, int[] inorder,int ileft,int iright){
if(pleft>pright||ileft>iright){
return null;
}
int i=preorder[pleft];
TreeNode node=new TreeNode(i);
int index=ileft;
while(inorder[index]!=i){
index++;
}
int leftLength=index-ileft;
node.left=buildTree(preorder,pleft+1,pleft+leftLength,inorder,ileft,index-1);
node.right=buildTree(preorder,pleft+leftLength+1,pright,inorder,index+1,iright);
return node;
}
}
网友评论