该levelOrder
方法需要递归调用自身来执行级别顺序遍历。我在如何将(这个)添加到累加器时遇到了麻烦。这就是我到目前为止所拥有的。
public class BinaryTreeNode<T> {
private BinaryTreeNode<T> left;
private BinaryTreeNode<T> right;
private T data;
public BinaryTreeNode() {
this(null, null, null);
}
public BinaryTreeNode(T theData) {
this(theData, null, null);
}
public BinaryTreeNode(T theData, BinaryTreeNode<T> leftChild,
BinaryTreeNode<T> rightChild) {
data = theData;
left = leftChild;
right = rightChild;
}
public void levelOrder(
SortedMap<Integer, List<BinaryTreeNode<T>>> accumulator, int depth) {
accumulator.put(depth, this);// add (this) to accumulator
if (left != null) {
left.levelOrder(accumulator, depth);// if (left) is not null invoke
// this method for left
}
if (right != null) {
right.levelOrder(accumulator, depth);// do the same for (right)
}
}
}