使用前序和中序构造二叉树


public class Test1 {
    public static void main(String[] args) throws InterruptedException {
        String perOrderStr = "ABHFDECKG";//前序序列
        String inOrderStr = "HBDFAEKCG";//中序序列
        BiTree node = createBiTree(perOrderStr, inOrderStr);
        //输出前序遍历验证正确性
        BiTree.preOrdertrasver(node);
    }
    static class BiTree {
        char data;
        BiTree left;
        BiTree right;
        public BiTree(char data) {
            this.data = data;
        }
        public static void preOrdertrasver(BiTree tree) {
            if (tree != null) {
                System.out.print(tree.data);
                preOrdertrasver(tree.left);
                preOrdertrasver(tree.right);
            }
        }
    }
    static BiTree createBiTree(String preOrderStr, String inOrderStr) {
        if (preOrderStr.length() == 0 || inOrderStr.length() == 0) {
            return null;
        }
        //树的根节点
        char root = preOrderStr.charAt(0);
        //创建节点
        BiTree node = new BiTree(root);
        //左右子树的根节点索引
        int index = inOrderStr.indexOf(root);
        //左子树str
        String leftSubTreeStr = inOrderStr.substring(0, index);
        //右子树str
        String rightSubTreeStr = inOrderStr.substring(index + 1);
        node.left = createBiTree(preOrderStr.substring(1, index + 1), leftSubTreeStr);
        node.right = createBiTree(preOrderStr.substring(index + 1), rightSubTreeStr);
        return node;
    }
}

你可能感兴趣的:(使用前序和中序构造二叉树)