重建二叉树

来源:互联网 发布:淘宝分期付款只有花呗 编辑:程序博客网 时间:2024/06/07 07:59

题目:输入某二叉树的先序遍历和中序遍历的结果,请重建出该二叉树。假设输入的前序遍历和中序遍历的结果中没有重复的数字。例如输入的前序遍历序列{1,2,4,7,3,5,6,8}和中序遍历序列{4,7,2,1,5,3,8,6},则重建二叉树并输出它的头结点。二叉树结点的定义如下:

class BiTree{int value;BiTree lchild,rchild;}
分析:在二叉树的先序遍历中,第一个数字是根节点。但是在中序遍历中,根结点的值在序列的中间,左子树的节点的值位于根结点的左边,而右子树的值位于根结点的右边。因此我们需要扫描中序遍历序列,才能找到根节点的值。 可以用递归的方法构造二叉树。

代码如下:

package Tree;class BiTree {int value;BiTree lchild, rchild;public BiTree(int value) {this.value = value;lchild = null;rchild = null;}public int getValue() {return value;}public void setValue(int value) {this.value = value;}public BiTree getLchild() {return lchild;}public void setLchild(BiTree lchild) {this.lchild = lchild;}public BiTree getRchild() {return rchild;}public void setRchild(BiTree rchild) {this.rchild = rchild;}}public class BineryTree {public static BiTree ConstructCore(int[] preOder, int[] inOder,int startpreOder, int startinOder, int endpreOder, int endinOder) {int rootValue = preOder[startpreOder];BiTree root = new BiTree(rootValue);// 在中序遍历中找到根节点int mid = startinOder;while (mid <= endinOder && inOder[mid] != rootValue)++mid;int leftLength = mid - startinOder;int leftPreOderEnd = startpreOder + leftLength;if (leftLength > 0) {// 构建左子树root.setLchild(ConstructCore(preOder, inOder, startpreOder + 1,startinOder, leftPreOderEnd, mid - 1));}if (leftLength < endpreOder - startpreOder) {// 构建右子树root.setRchild(ConstructCore(preOder, inOder, leftPreOderEnd + 1,mid + 1, endpreOder, endinOder));}return root;}public static void inOrderTraverse(BiTree node) {if (node == null)return;inOrderTraverse(node.lchild);System.out.print(node.value + " ");inOrderTraverse(node.rchild);}public static void main(String[] args) {int preOder[] = { 1, 2, 4, 7, 3, 5, 6, 8 };int inOder[] = { 4, 7, 2, 1, 5, 3, 8, 6 };BiTree trr = ConstructCore(preOder, inOder, 0, 0, 7, 7);inOrderTraverse(trr);}}

0 0
原创粉丝点击