我正在从Data Structures中查看旧测试,我无法弄清楚如何在Tree类中实现printtree(int level)
方法。我被限制使用这种结构。我无法确定在没有root.right
或root.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);
}
}
答案 0 :(得分:1)
你只需要改变3件事:
root
方法this
更改为printTree(int level)
if(this == null)
的展示位置使用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;
}