【发布时间】:2013-10-29 12:43:46
【问题描述】:
就在我坐下来为 morris 中序遍历编写代码之前,我尝试了这个示例,但对于它在这种特殊情况下的工作方式有点困惑:
80
/ \
60 100
\ /
70 90
/
65
/
63
\
64
第 1 步:
60
\
70
/ \
65 80
/ \
63 100
\ /
64 90
据我了解,下一步的算法 70 会成为 65 的右孩子,那么 60 会发生什么?我很确定我错过了一些微不足道的东西,但很遗憾无法找到它。
public void MorrisInorder() {
BSTNode<T> p = root, tmp;
while (p != null)
if (p.left == null) {
visit(p);
p = p.right;
}
else {
tmp = p.left;
while (tmp.right != null && // go to the rightmost node of
tmp.right != p) // the left subtree or
tmp = tmp.right; // to the temporary parent of p;
if (tmp.right == null) {// if 'true' rightmost node was
tmp.right = p; // reached, make it a temporary
p = p.left; // parent of the current root,
}
else { // else a temporary parent has been
visit(p); // found; visit node p and then cut
tmp.right = null; // the right pointer of the current
p = p.right; // parent, whereby it ceases to be
} // a parent;
}
}
我正在遵循 morris 中序遍历的代码。
【问题讨论】:
-
我曾经编写过中序遍历,而不是 morris 中序遍历,不同之处在于它使用线程而不是堆栈或递归。我想问你是否了解基本的中序遍历,或者你只被莫里斯版本卡住了。
-
@Setilă 我非常了解中序遍历,并且我刚刚编写了一个带有添加、删除、搜索方法的线程树。我为 morris inorder 遵循的代码如上。
标签: algorithm binary-tree binary-search-tree traversal tree-traversal