【问题标题】:Java - Indented list from a treeJava - 来自树的缩进列表
【发布时间】:2017-05-11 23:15:34
【问题描述】:

我的一个关于树木的大学实验室要求我们编写一个名为toIndentedString() 的方法。说明如下:

另一种将树的内容表示为字符串的方法是使用缩进列表。在这里,我们首先表示根,然后每个 它的子子树,由两个空格缩进(这是应用的 递归)。对于示例树,我们会得到:

food
  meat
    chicken
    beef
    fish
      salmon
      cod
      tuna
      shark
  fruit
  vegetable
    cabbage

这是示例树的示意图:

这是我当前的代码:

package week10;

import java.util.*;

/**
 * Skeleton of the recursive implementation of a general tree.
 * 
 * @author Michael Albert
 * @param <T> The type of values stored in the tree.
 */
public class Tree<T> {

    private T rootValue;
    private List<Tree<T>> children;

    public Tree(T rootValue, List<Tree<T>> children) {
        this.rootValue = rootValue;
        this.children = children;
    }

    public Tree(T rootValue) {
        this(rootValue, new ArrayList<Tree<T>>());
    }

    public int size() {
        int count = 1;
        for (Tree<T> child : children) {
            count += child.size();
        }
        return count;
    }

    public int maxDegree() {
        // Get the number of immediate children
        int numChildren = this.children.size();

        // Find the max of all children
        int maxOfChildren = 0;
        for (Tree<T> child : children) {
            maxOfChildren = Math.max(maxOfChildren, child.maxDegree());
        }

        // return the greater of immediate child or max of children
        return Math.max(numChildren, maxOfChildren);
    }

    public void add(Tree<T> child) {
        children.add(child);
    }

    public Tree<T> find(T value) {
        if (rootValue.equals(value)) {
            return this;
        }
        for (Tree<T> child : children) {
            Tree<T> match = child.find(value);
            if (match != null) {
                return match;
            }
        }
        return null;
    }

    public List<T> postOrder() {
        ArrayList<T> list = new ArrayList<T>();
        for (Tree<T> child : children) {
            if (!child.children.isEmpty()) {
                child.postOrder();
            } else {
                //list.add(child);
                System.out.println(child);
            }
        }
        return list;
    }

    public String toString() {
        if (children.isEmpty()) {
            return rootValue.toString();
        }
        return rootValue.toString() + ' ' + children.toString();
    }

    public String toIndentedString() {
        // implement this method
        return "Not implemented yet!";
    }

    /** A helper method for testing (used by main).  Searches tree for
     *  the given target and adds white space separated children to
     *  the tree matching target if there is one.
     *
     * @param target the root value to seach for.
     * @param children a white space separated list of children to add
     * to the tree whose value matches target.
     */
    private static void addChildren(String target, String children) {
        Tree<String> parent = tree.find(target);
        if (parent != null) {
            for (String child : children.split(" ")) {
                parent.add(new Tree<>(child));
            }
        }
    }

    /** A tree instance used for testing. */
    private static Tree<String> tree;

    /**
     * Entry point of the program (used for testing).
     *
     * @param args command line arguments are not used.
     */
    public static void main(String[] args) {
        System.out.println("Creating tree\n-------------");
        tree = new Tree<>("food");
        System.out.print(tree + "\nsize: " + tree.size());
        System.out.println(", max degree: " + tree.maxDegree());
        System.out.println("\nAdding children\n----------------");
        addChildren("food", "meat fruit vegetable");
        System.out.print(tree + "\nsize: " + tree.size());
        System.out.println(", max degree: " + tree.maxDegree());
        System.out.println("\nAdding deeper children\n----------------------");
        addChildren("meat", "chicken beef fish");
        addChildren("fish", "salmon cod tuna shark");
        addChildren("vegetable", "cabbage");
        System.out.print(tree + "\nsize: " + tree.size());
        System.out.println(", max degree: " + tree.maxDegree());
        System.out.println("\nPostorder\n---------");
        System.out.println(tree.postOrder());
        System.out.println("\nIndented string\n---------------");
        System.out.print(tree.toIndentedString());
    }

}

如何实现此方法,以便递归缩进子树?

【问题讨论】:

  • 你在打印带有缩进的树时提到过这个example。
  • 您在此处尝试执行的操作与depth-first search 有关。首先尝试实现它,然后跟踪缩进的数量并按照规范打印树。

标签: java string recursion tree


【解决方案1】:

这是一个简单的递归实现:

public String toIndentedString() {
    StringBuilder sb = new StringBuilder(rootValue.toString());
    for (Tree<T> child : children) {
        sb.append('\n');
        sb.append(child.toIndentedString().replaceAll("(?m)^", "  "));
    }
    return sb.toString();
}

Ideone Demo

首先,将根值转换为字符串,然后添加由换行符连接的每个子缩进字符串。要缩进子字符串的每一行,请使用替换正则表达式,在每行的前面添加一个缩进。

【讨论】:

  • 谢谢!这很有帮助。我有一个问题/问题,我需要最终输出以休息结束,因此“]”显示在“蔬菜”下面的行上。目前它正在返回,以便它们在同一条线上。蔬菜]蔬菜]i.imgur.com/C8HUfn2.png
  • 嗯,要仅操作最终输出,您只需将换行符附加到 toIndentedString 的输出中,或者将整个实现移动到单独的私有方法中,然后附加一个换行符到私有方法的输出。
  • 嗯,这个编辑似乎仍然产生完全相同的问题?
  • 对不起,我的编辑只是为了进一步简化代码,而不是解决您的评论。 Here's an example 怎么做你说的。
  • 一切顺利!不知道为什么当我最初尝试分离方法时它没有正确输出,但是哦。非常感谢您的帮助
【解决方案2】:

根据main 方法中提供的示例,您有一个字符串节点树(您的类称为“树”,但术语“节点”更适合它们的含义)。

正如您的作业所暗示的,递归是这里的关键。您需要递归地遍历树节点,并在每次递归调用时传递不断增加的缩进级别。类似的东西。

    private static final String INDENT_STRING = "  ";

    public String toIndentedString() {
        StringBuilder sb = new StringBuilder();
        this.buildIndentedString(sb, 0);
        return sb.toString();
    }

    private void buildIndentedString(StringBuilder builder, int indentationLevel) {
        for (int i = 0; i < indentationLevel; i++) {
            builder.append(INDENT_STRING);
        }
        builder.append(rootValue != null ? rootValue.toString() : "null");
        builder.append('\n');
        // Recurse over the children, building the tree with a deeper indentation level.
        for (Tree t : this.children) {
            t.buildIndentedString(builder, indentationLevel+1);
        }
    }

递归方法buildIntentedString 是所有递归发生的地方。首先,我们将缩进间距附加到 StringBuilder。然后,我们将当前节点的对象附加为一个字符串(如果我们有一个空对象,则为“空”)。最后,我们递归:迭代当前节点的子节点并执行相同的操作,并增加缩进级别。您的示例的输出最终应该是这样的:

food
  meat
    chicken
    beef
    fish
      salmon
      cod
      tuna
      shark
  fruit
  vegetable
    cabbage

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2023-03-30
    • 2014-03-11
    • 2021-01-23
    • 1970-01-01
    • 1970-01-01
    • 2011-10-08
    相关资源
    最近更新 更多