已知二叉树的先序遍历序列和中序遍历序列,重构出二叉树。
算法简介:
如上图所示的二叉树,其先序遍历序列为:a b d c e f 中序序列为:d b a e c f
首先可以知道根结点为先序的第一个元素即 a ,(a b d c e f)
再由中序序列可知对于根结点a 其中序序列的左子树为db 右子树为ecf (d b a e c f)
接下来可以得到先序序列 左子树为bd 右子树为 ecf
接着对其左子树,右子树的先序序列后序序列重复上述步骤即可完成二叉树的重构。
代码实现如下:
public Node reconstructBintree(String preOrd,String midOrd) {
//先序 + 中序 重构二叉树
if(preOrd.length() == 0) {
return null;
}
Node root = new Node(preOrd.charAt(0));
int indexRoot = midOrd.indexOf(preOrd.charAt(0));
root.left = reconstructBintree(
preOrd.substring(1,indexRoot+1),//刨除根结点
midOrd.substring(0,indexRoot));//根结点的左侧
root.right = reconstructBintree(
preOrd.substring(indexRoot+1),
midOrd.substring(indexRoot+1));//根结点的右侧
return root;
}
一点分析:
其后序+中序也可以重构二叉树,其实现也大同小异,只不过其根结点取后序遍历序列的最后一个元素。
但是先序+后序是无法重构二叉树的,先序+中序子所以能够重构二叉树,是由于通过根结点以及中序可以得到左右子树的长度,这点很重要。先序+后序是无法得到左右子树的长度,因此亦无法重构二叉树。