1
levelOrder
方法需要遞歸調用自身以執行級別遍歷。我在如何添加(this)到累加器時遇到了問題。這是我迄今爲止所擁有的。級別遍歷的遞歸方法
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)
}
}
}
謝謝。這很好。 – Yahwe 2013-04-29 00:41:02