目录
题目:
输入某二叉树的前序遍历和中序遍历的结果,请重建该二叉树。假设输入的前序遍历和中序遍历的结果中都不含重复的数字。例如,输入前序遍历序列{1,2,4,7,3,5,6,8}和中序遍历序列{4,7,2,1,5,3,8,6},则重建如图2.6所示的二叉树并输出它的头节点。二叉树节点的定义如下:stuct BinaryTreeNode {
int m_nValue;
BinaryTreeNode* m_pLeft;
BinaryTreeNode* m_right;
}
思路:
在二叉树的前序遍历序列中,第一个数字总是树的根节点的值。但在中序遍历序列中,根节点的值在序列的中间,左子树的节点的值位于根节点的值的左边,而右子树的节点的值位于根节点的值的右边。因此我们需要扫描中序遍历序列,才能找到根节点的值。步骤:
1.前序遍历序列的第一个数字1就是根节点的值。扫描中序遍历序列,就能确定根节点的值的位置。根据中序遍历的特点,在根节点的值1前面的3个数字都是左子树的值,位于1后面的数字都是右子树节点的值。2.由于在中序遍历序列中,有3个数字是左子树节点的值,因此左子树共有3个左子节点。同样,在前序遍历序列中,根节点后面的3个数字就是3个左子树的节点的值,再后面的所有数字都是右子树节点的值。这样我们就在前序遍历和中序遍历两个序列中分别找到了左、右子树对应的子序列。
3.既然我们已经分别找到了左、右子树的前序遍历序列和中序遍历序列,我们可以用同样的方法分别构建左、右子树。也就说,接下来的事情可以用递归的方法去完成。
代码:
package test;
public class BinaryTreeNode {
public static void main(String[] args) {
int[] pre = {1, 2, 4, 7, 3, 5, 6, 8};
int[] in = {4, 7, 2, 1, 5, 3, 8, 6};
TreeNode root = reConstructBinaryTree(pre, in);
printTree(root);
}
private static void printTree(TreeNode root) {
if(root != null) {
printTree(root.left);
System.out.println(root.value);
printTree(root.right);
}
}
public static TreeNode reConstructBinaryTree(int[] pre, int[] in) {
//对输入数据进行校验
if(pre == null || in == null || pre.length != in.length)
return null;
return construct(pre, 0, pre.length - 1, in, 0, in.length - 1);
}
private static TreeNode construct(int[] pre, int ps, int pe, int[] in, int is, int ie) {
//5.递归结束条件
if(ps > pe)
return null;
//1.获取根节点
int root = pre[ps];
//2.扫描中序遍历序列,确定根节点的位置
int index = is;
while(index <= ie && root != in[index])
index++;
//3.创建根节点
TreeNode node = new TreeNode(root);
//4.创建左右子节点
node.left = construct(pre, ps + 1, ps + index - is, in, is, index - 1);
node.right = construct(pre, ps + index - is + 1, pe, in, index + 1, ie);
return node;
}
static class TreeNode {
int value;
TreeNode left;
TreeNode right;
public TreeNode(int value) {
this.value = value;
}
}
}