树打印树方法

时间:2013-12-06 23:50:50

标签: java recursion tree

我正在从Data Structures中查看旧测试,我无法弄清楚如何在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);

   }
}

1 个答案:

答案 0 :(得分:1)

你只需要改变3件事:

  1. root方法
  2. 中的每个位置将this更改为printTree(int level)
  3. 应先检查if(this == null)的展示位置
  4. 使用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;
    }