繁体   English   中英

树打印树方法

[英]Tree Print Tree Method

我正在通过数据结构检查我的旧测试,并且我无法弄清楚如何在Tree类中实现printtree(int level)方法。 我仅限于使用此结构。 我无法弄清楚没有root.rightroot.left可以使用的实现,这非常令人沮丧。

/*
    Exam 2. Problem 2. 03/09/2012
*/
import java.util.List;
import java.util.ArrayList;

/**
   A tree in which each node has an arbitrary number of children.
*/
public class Tree
{
   private Node root;

   class Node
   {
      public Object data;
      public List<Node> children;

      /**
         Computes the size of the subtree whose root is this node.
         @return the number of nodes in the subtree
      */
      public int size()
      {
         int sum = 0;
         for (Node child : children) { sum = sum + child.size(); }
         return 1 + sum;
      }

      public int leaves() {
          int count = 0;
          for (Node child : children) { 
              if (child.size() == 1) {
                  count = count + 1;
              } else {
                  count = count + child.leaves();
              }
          }
          if (count == 0) {
              count = count + 1;
          }
          return count;
      }

      public String printTree(int level) {
          String S = "";
            S += root.data + " (level:" + level + ") ";
            if (root != null) {
                return S;
            }
            if (root.children != null) {
                S += root.printTree(level + 1);
            }

            return S;
      }

   }

   /**
      Constructs an empty tree.
   */
   public Tree()
   {
      root = null;
   }

   /**
      Constructs a tree with one node and no children.
      @param rootData the data for the root
   */
   public Tree(Object rootData)
   {
      root = new Node();
      root.data = rootData;
      root.children = new ArrayList<Node>();
   }

   /**
      Adds a subtree as the last child of the root.
   */
   public void addSubtree(Tree subtree)
   {
      root.children.add(subtree.root);
   }

   /**
      Computes the size of this tree.
      @return the number of nodes in the tree
   */
   public int size() 
   {
      if (root == null) { return 0; }
      else { return root.size(); }
   }

   public int leaves() {
       Node newNode = root;
       if (root == null) { return 0; }
       else { return root.leaves(); }
   }

   public String printTree() {
       return root.children.printTree(0);

   }
}

您只需要更改3件事:

  1. printTree(int level)方法中的每个位置都将root更改this
  2. 应该先检查if(this == null)的位置
  3. 使用for循环打印所有子项

     public String printTree(int level) { String S = ""; // notice the change to '==' if (this == null) return S; S += this.data + " (level:" + level + ") "; // notice the for loop if( this.children != null) for(Node child : this.children) S += child.printTree(level + 1); return S; } 

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM