先说说原理吧:
- 前序遍历的第一个节点必然是树的根节点
- 通过第1个节点将中序遍历分割为两部分,左边的就是树的左子树的节点,右边就是树的右子树的节点
- 重复1,2步,直至构建一颗完整的二叉树
Java代码:
// 前序遍历序列{1,2,4,7,3,5,6,8}和中序遍历序列{4,7,2,1,5,3,8,6}
public TreeNode reConstructBinaryTree(int[] pre, int[] in)
{
if (pre == null || in == null || pre.length != in.length)
return null;
TreeNode pHeadNode = new TreeNode(pre[0]);
int i = 0;
for (i = 0; i < in.length; i++)
if (pre[0] == in[i])
break;
pHeadNode.left = reConstructBinaryTree(pre, in, 1, 0, i - 1);
pHeadNode.right = reConstructBinaryTree(pre, in, i + 1, i + 1,
in.length - 1);
return pHeadNode;
}
/**
* @param pre 前序遍历的数组
* @param in 中序遍历的数组
* @param mid 根节点的值
* @param start 子树的开始节点
* @param end 子树的开始节点
* @return
*/
public TreeNode reConstructBinaryTree(int[] pre, int[] in, int mid,
int start, int end)
{
if (end < start)
return null;
TreeNode node = new TreeNode(pre[mid]);
if (end == start)
return node;
int i = 0;
for (i = start; i <= end; i++)
if (pre[mid] == in[i])
break;
if (i == start)
node.left = null;
else
node.left = reConstructBinaryTree(pre, in, mid + 1, start,
i - 1);
if (i == end)
node.right = null;
else
node.right = reConstructBinaryTree(pre, in, mid + 1 + i
- start, i + 1, end);
return node;
}