3 回答

TA貢獻1898條經(jīng)驗 獲得超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條經(jīng)驗 獲得超6個贊
您的方法看起來像 DFS 方法它可能不遵循該方法。嘗試在此處使用 Queue 它將幫助您正確遍歷。因為它將遵循 BFS 方法,以便您可以逐層遍歷。添加第一個左節(jié)點,然后添加右節(jié)點并按照以下步驟。

TA貢獻1830條經(jīng)驗 獲得超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
使用僅填充根節(jié)點的“下一輪”列表開始該過程。
重復(fù)直到“下一輪”節(jié)點列表變?yōu)榭栈蛘吣业搅四檎业膬?nèi)容。
添加回答
舉報