3 回答
TA贡献1898条经验 获得超8个赞
我就是这样做的。
private void levelOrder(BinaryNode root) {
if (root == null) {
return;
}
Queue<BinaryNode> q = new LinkedList<>();
// Pushing root node into the queue.
q.add(root);
// Executing loop till queue becomes
// empty
while (!q.isEmpty()) {
BinaryNode curr = q.poll();
System.out.print(curr.element + " ");
// Pushing left child current node
if (curr.left != null) {
q.add(curr.left);
}
// Pushing right child current node
if (curr.right != null) {
q.add(curr.right);
}
}
}
TA贡献1797条经验 获得超6个赞
您的方法看起来像 DFS 方法它可能不遵循该方法。尝试在此处使用 Queue 它将帮助您正确遍历。因为它将遵循 BFS 方法,以便您可以逐层遍历。添加第一个左节点,然后添加右节点并按照以下步骤。
TA贡献1830条经验 获得超9个赞
将整个搜索视为一系列“轮”,每个级别一个“轮”。
在每一轮中:
- initialize a "next round" list of nodes to empty
- process a prepared list of nodes (the ones that are at that level and thus to be searched in that round) whereby for each node :
- do the actual comparison
- add all the node's child nodes to the "next round" list
使用仅填充根节点的“下一轮”列表开始该过程。
重复直到“下一轮”节点列表变为空或者您找到了您要查找的内容。
添加回答
举报