指导员是正确的。一次遍历就足够了。
遍历原始的二叉树,当你走这棵树时创建新的ThreadedNode
。
public static <T> ThreadedNode<T> thread(BinaryNode<T> root) {
// We'll be keeping track of the "previous" node as we go, so use
// a recursive helper method. At first, there is no previous.
return threadHelper(root, null);
}
private static <T> ThreadedNode<T> threadHelper(BinaryNode<T> n, ThreadedNode<T> previous) {
// Create a new threaded node from the current root. Note that the threaded nodes
// are actually created in "preorder". Assume the ThreadedNode constructor sets
// the left, right, threadLeft, and threadRight fields to null.
ThreadedNode<T> t = new ThreadedNode<T>(n.getData());
// First go down the left side, if necessary.
if (n.getLeft() != null) {
// If there is a left child we have to descend. Note that as we go down the
// left side the previous doesn't change, until we start "backing up".
t.left = threadHelper(n.getLeft(), previous);
previous = t.left;
} else {
// If there is no left child, connect our left thread to the previous.
t.threadLeft = previous;
}
// Now before we go down the right side, see if the previous
// node (it will be in the left subtree) needs to point here.
if (previous != null && previous.right == null) {
previous.threadRight = t;
}
if (n.getRight() != null) {
// If there is a right child we can descend the right. As we go down we
// update previous to the current node. We do this just by passing the current
// node as the second parameter.
t.right = threadHelper(n.getRight(), t);
} else {
// No right child, no worries. We'll hook up our thread-right pointer
// later.
}
return t;
}
考虑树(A(B(D)())C)。你在中序遍历中的第一个节点是D.没有以前的节点。因此,保存D像以前一样。然后你点击的下一个节点是B.前一个节点是D,它没有正确的子节点,所以添加一个从D到B的带螺纹的右指针。然后设置在B之前并继续。接下来你击中A.B没有正确的孩子,所以添加一个从B到A的正确的链接.A有一个正确的孩子继续,设置在A之前。下一个节点是C. C没有离开孩子,所以添加一个从C中的左侧链接到前一个的当前值,即A.
你是什么意思? – user1072706