【发布时间】:2021-07-31 19:07:34
【问题描述】:
在没有递归的情况下遍历数组二叉树时遇到了麻烦。 我希望有人能告诉我我做错了什么。为简单起见,代码保持简单。
请注意:不允许添加Iterator等其他方法来检查是否有hasNext()等。
现在我只想打印所有的键(包括子键),希望我能完成剩下的学习!
非常感谢您的帮助。
public class BTree {
private Node root;
public BTree(Node root) {
this.root = root;
}
public int getMaxKey() {
Node copy = root;
for (int i = 0; copy.child != null && i < copy.child.length; i++) {
System.out.println("key: " + copy.key); // output: 15, 80
if (copy.child != null) {
copy = copy.child[i];
}
}
return 0;
}
}
public class Node {
public int key;
public Node[] child;
public Node(int key, Node[] child) {
this.key = key;
this.child = child;
}
}
public class NodeMain {
public static void main(String[] args) {
Node[] lv1Nodes = new Node[2];
lv1Nodes[0] = new Node(25, null);
lv1Nodes[1] = new Node(99, null);
Node[] lv0Nodes = new Node[2];
lv0Nodes[0] = new Node(80, lv1Nodes);
lv0Nodes[1] = new Node(5, null);
Node root = new Node(15, lv0Nodes);
BTree bTree = new BTree(root);
int maxKey = bTree.getMaxKey(); // output should be 99
System.out.println(maxKey);
}
}
【问题讨论】:
标签: java