解法1
package tree.leveltraversal;
import tree.Node;
import tree.myavl.BalanceTree;
import java.util.LinkedList;
import java.util.Queue;
/**
* Created by lijie35 on 2020-01-21 10:45 AM .
*/
public class LevelTraversal2 {
public static void main(String[] args) {
BalanceTree bl=new BalanceTree();
bl.put(10);
bl.put(5);
bl.put(15);
bl.put(4);
bl.put(7);
bl.put(11);
bl.put(16);
Queue queue1 = new LinkedList();
queue1.add(bl.root);
LevelTraversal2.cycle(queue1);
System.out.println(queue1);
}
public static void cycle(Queue<Node> queue ) {
if (queue.size() == 0)
return;
while (queue.size() > 0) {
Node poll = queue.poll();
System.out.println(poll.val);
if (poll.leftChild != null)
queue.add(poll.leftChild);
if (poll.rightChild != null)
queue.add(poll.rightChild);
}
cycle(queue);
}
}
package tree.leveltraversal;
import tree.Node;
import tree.myavl.BalanceTree;
import java.util.LinkedList;
import java.util.Queue;
/**
* Created by lijie35 on 2020-01-21 10:45 AM .
*/
public class LevelTraversal1 {
public static void main(String[] args) {
BalanceTree bl=new BalanceTree();
bl.put(10);
bl.put(5);
bl.put(15);
bl.put(4);
bl.put(7);
bl.put(11);
bl.put(16);
Queue queue1 = new LinkedList();
Queue queue2 = new LinkedList();
queue1.add(bl.root);
LevelTraversal1.cycle(queue1,queue2);
System.out.println(queue2);
}
public static void cycle(Queue<Node> queue ,Queue<Node> all) {
if (queue.size() == 0)
return;
Queue queue1 = new LinkedList();
while (queue.size() > 0) {
Node poll = queue.poll();
System.out.println(poll.val);
all.add(poll);
if (poll.leftChild != null)
queue1.add(poll.leftChild);
if (poll.rightChild != null)
queue1.add(poll.rightChild);
}
cycle(queue1,all);
}
}
来源:CSDN
作者:javalj_hz
链接:https://blog.csdn.net/l4oli/article/details/104061805