-
/**
-
* 前序遍历和中序遍历创建二叉树
-
Pre 前序遍历的数组 In 中序遍历的数组 lpre 前序遍历数组开始位置 hpre前序遍历结束位置
-
* lin前序遍历数组开始位置 hin前序遍历结束位置
-
*/
-
@Override
-
public TreeNode PreInCreat(int[] Pre, int[] In, int lpre, int hpre, int lin, int hin) {
-
TreeNode root = new TreeNode(0);
-
if (Pre.length == 0 || In.length == 0) {
-
return null;
-
}
-
root.val = Pre[lpre];
-
int i;
-
for (i = lin; In[i] != Pre[lpre]; i++)
-
;// 得到中序遍历数组的根节点位置
-
int lleng = i - lin;// 左边子树的长度
-
int rleng = hin - i;// 右边子树的长度
-
-
if (lleng > 0) {
-
root.leftchild = PreInCreat(Pre, In, lpre + 1, lpre + lleng, lin, lin + lleng - 1);
-
-
} else {
-
root.leftchild = null;
-
}
-
if (rleng > 0) {
-
root.rightchild = PreInCreat(Pre, In, hpre - rleng + 1, hpre, hin - rleng + 1, hin);
-
-
} else {
-
root.rightchild = null;
-
}
-
-
return root;
-
}
|