先序中序得到后序 (MEDIUM)

思路

ABDGCEFH
DGBAECHF
这里写图片描述
输入前序ABDGCEFH,中序DGBAECHF,可以得出
A为该二叉树的根节点
1: BDG为该二叉树左子树的前序
2: DGB为该二叉树左子树的中序
A BDG CEFH
DGB A ECHF
根据1和2可以构建一棵左子树
3: CEFH为该二叉树右子树的前序
4: ECHF为该二叉树右子树的中序
根据3和4可以构建一个右子树
执行至该步骤的时候就得到了该二叉树的云结构,如图2所示,A为根节点,BDG在它的左子树上,CEFG在它的右子树上。
如此递归即可以构建一棵完整的二叉树

这里写图片描述

源码

class BTree {
    char data;
    BTree left;
    BTree right;
}

public class NodeTree {

    //s1先序第一个字符位置,s2中序第一个字符位置;l1先序列最后一个字符的位置,l2中序列最后一个字符的位置
    public void Create(BTree root, String first, String mid, int s1, int l1, int s2, int l2) {
        root.data = first.charAt(s1);                  //根节点为先序的第一个字符
        int rootpos = mid.indexOf(first.charAt(s1));   //先序第一个字符在中序中的位置
        int len = rootpos - s2;                        //被截取的字符串长度(不包括根)
        if (rootpos > s2) {         //根位置在中序首字符之后
            root.left = new BTree();
            Create(root.left, first, mid, s1 + 1, s1 + len, s2, rootpos - 1);
        }
        if (rootpos < l2) {         //根在中序结尾之前
            root.right = new BTree();
            Create(root.right, first, mid, s1 + len + 1, l1, rootpos + 1, l2);

        }
    }

    public void show(BTree root) {
        if (root.left != null) {
            show(root.left);
        }
        if (root.right != null) {
            show(root.right);
        }
        System.out.print(root.data);
    }

    public static void main(String[] args) {
        String first = "ABDGCEFH";
        String mid = "DGBAECHF";
        NodeTree nodeTree = new NodeTree();
        BTree root = new BTree();
        nodeTree.Create(root, first, mid, 0, first.length() - 1, 0, mid.length() - 1);
        nodeTree.show(root);
    }

}

这里写图片描述

参考:
http://blog.csdn.net/xiaokanfengyun007/article/details/37917773
http://www.cnblogs.com/xiaodeyao/p/5404881.html

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值