- html - 出于某种原因,IE8 对我的 Sass 文件中继承的 html5 CSS 不友好?
- JMeter 在响应断言中使用 span 标签的问题
- html - 在 :hover and :active? 上具有不同效果的 CSS 动画
- html - 相对于居中的 html 内容固定的 CSS 重复背景?
我正在编写按顺序打印二叉搜索树的方法。我找到了一种方法来做到这一点,但它需要在打印节点时删除或使节点无效。下面是我的代码:
public String printKeysInOrder() {
String output = "";
if (isEmpty()) return "()";
else{
int i = 0;
while(i!=size()){
Node x = root;
int loopBreak = 0;
while(loopBreak!=1){
if(x.left != null) x = x.left;
else if (x.right != null){
output = output + " " + x.val;
x.key = null;
x = x.right;
i++;
}
else{
output = output + " " + x.val;
x.key = null;
loopBreak = 1;
}
}
i++;
}
}
return output;
}
对于树:
_7_
/ \
_3_ 8
/ \
1 6
\ /
2 4
\
5
它应该打印“1 2 3 4 5 6 7 8”
代码的工作方式是它倾向于在树中向左移动,直到它不能再向左移动为止,然后它将该节点的值存储在字符串输出中,使节点键等于 null(因此 future 的迭代循环不会沿着该树向下移动)并在可能的情况下向右移动或围绕循环迭代回来。
尽管我在使节点等于 null 时遇到了麻烦,因为当执行代码时(通过 junit 测试),代码无法识别该 null 键并无论如何都会遍历该子树?任何人都可以帮助我或告诉我如何制作它,以便 future 迭代中的 x.left 和 x.right 指针将节点识别为空吗?
最佳答案
您不需要取消或删除节点,您需要遍历算法。
此处提供的有序遍历无需进行重大修改即可工作: http://www.javabeat.net/binary-search-tree-traversal-java/
另一种面向对象的方法是提供一个可按顺序遍历的访问者,它允许您提供在每个节点执行的操作,无论是打印、收集、映射还是其他操作。
关于java - 尝试打印时二分查找树的指针问题,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/33637698/
我正在尝试编写一个程序,在名为 items 的数组中进行顺序搜索和二分搜索,该数组具有 10000 个已排序的随机 int 值。第二个名为 targets 的数组加载了 1000 个 int 值(50
当我尝试使用图表并为其编写一些代码但没有成功时,我遇到了一个问题:/!! 我想创建一些东西来获取图形数据并检查它是否:1- 连接2-二分法3-有循环4-是一棵树 所以我想知道,例如,是否可以将其写入以
我是一名优秀的程序员,十分优秀!