美文网首页data structure and algorithms
使用前序和中序构造二叉树

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

作者: spraysss | 来源:发表于2018-05-15 13:40 被阅读0次
    
    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;
        }
    }
    

    相关文章

      网友评论

        本文标题:使用前序和中序构造二叉树

        本文链接:https://www.haomeiwen.com/subject/sbijdftx.html