从前序与中序遍历序列构造二叉树
根据一棵树的前序遍历与中序遍历构造二叉树。
注意:
你可以假设树中没有重复的元素。
例如,给出
前序遍历 preorder = [3,9,20,15,7]
中序遍历 inorder = [9,3,15,20,7]
返回如下的二叉树:
3
/ \
9 20
/ \
15 7
思路+代码+注释:
public static TreeNode buildTree(int[] preorder, int[] inorder) {
if (preorder.length==0)
{
return null;
}
TreeNode root=new TreeNode(preorder[0]);
buildTree(root,preorder,0,preorder.length-1,inorder,0,inorder.length-1);
return root;
}
private static void buildTree(TreeNode root,int[] preorder,int lpreorder,int rpreorder,int[] inorder,int linorder,int rinorder)
{
if (lpreorder >= rpreorder && linorder>=rinorder)
{
return ;
}
TreeNode leftChildNode=null;
//确定左子树节点数
int count=0;
for (int i = linorder; i <= rinorder; i++) {
if (inorder[i]==root.val)
{
break;
}else {
count++;
}
}
if (count!=0)
{
if (rpreorder >= lpreorder+1)
{
leftChildNode=new TreeNode(preorder[lpreorder+1]);
}
}
TreeNode rightNode=null;
if (lpreorder+count+1 <= rpreorder)
{
rightNode=new TreeNode(preorder[lpreorder+count+1]);
}
root.left=leftChildNode;
root.right=rightNode;
//确定左子树
if (leftChildNode!=null)
{
buildTree(leftChildNode,preorder,lpreorder+1,lpreorder+count>rpreorder?rpreorder:lpreorder+count,inorder,linorder,linorder+count-1);
}
//确定右子树
if (rightNode!=null)
{
buildTree(rightNode,preorder,lpreorder+1+count,rpreorder,inorder,linorder+count+1,rinorder);
}
}