【问题标题】:Building a BinaryTree from an InOrder String Representation从 InOrder 字符串表示构建二叉树
【发布时间】:2021-11-23 03:33:35
【问题描述】:

我得到一个字符串,例如: (((!D!)B!)A((!F(!H!))C(!G!))) ,其中从来没有任何空格。一种 '!'表示节点的那一侧没有子节点。为了形象化,前面提到的字符串看起来像:https://i.stack.imgur.com/WywYm.png

我必须有一个构造函数,可以调用递归方法通过传入String来构建树,这就是我这里的:

public BinaryTree(String tree) {
    //build the tree from the inOrder representation of the tree
    //in the inOrder representation an empty tree is ! and a non-empty tree is (leftdataright)
    if(tree.charAt(0) == '!') root = null;
    root = buildTree(tree).root;
}

从这里我通过私有 BuildTree 方法进入,该方法应该使用递归并返回对完全组装树的根的引用。我的代码是:

private BinaryTree buildTree(String tree) {
    char data = tree.charAt(0);
    BinaryTree b1;
    BinaryTree b2;      
    if(tree.charAt(0) == '!') return new BinaryTree();
    b1 = buildTree(tree.substring(1, tree.length()));
    b2 = buildTree(tree.substring(1, tree.length()));
    return new BinaryTree(b1, data, b2);
}

我想我对 InOrder 表示感到困惑,在这种表示形式中,您不会遇到完整树的根,直到您进入字符串非常远。我当前的代码没有做任何事情,我完全不知道如何在不立即知道根的情况下完成此操作。如果有人可以更好地解释这一点以使我更接近解决方案,请告诉我。谢谢。

【问题讨论】:

    标签: java binary-tree inorder


    【解决方案1】:

    这样的事情怎么样:

    private static BinaryTree buildTree(String tree) {
        try {
            return buildTree(new StringReader(tree));
        } catch (IOException ex) {
            throw new RuntimeException(ex.getMessage());
        }
    }
    
    private static BinaryTree buildTree(Reader in) throws IOException {
        char c = (char)in.read();
        if (c == '!') {
            return null;
        } else if (c != '(') {
            throw new IOException("Syntax error");
        }
        BinaryTree left = buildTree(in);
        char data = (char)in.read();
        BinaryTree right = buildTree(in);
        c = (char)in.read();
        if (c != ')') {
            throw new IOException("Syntax error");
        }
        return new BinaryTree(left, data, right);
    }
    

    【讨论】:

      猜你喜欢
      • 2019-10-18
      • 2016-01-22
      • 2021-11-26
      • 1970-01-01
      • 2012-11-06
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2013-04-09
      相关资源
      最近更新 更多