JAVA多叉樹的BFS與DFS歷遍,筆記
public void bfsTree(){
? ? ? ?if (root == null) {
? ? ? ? ? ?return;
? ? ? ?}
? ? ? ?Queue<Node> queue = new LinkedList<>();
? ? ? ?queue.offer(root);
? ? ? ?while (!queue.isEmpty()) {
? ? ? ? ? ?Node tmpNode = queue.peek();
? ? ? ? ? ?System.out.println(queue.poll().value);
? ? ? ? ? ? ? ?if (tmpNode.children!=null){
? ? ? ? ? ? ? ?for (int i = 0; i < tmpNode.children.size(); i ?) {
? ? ? ? ? ? ? ? ? ?queue.add(tmpNode.children.get(i));
? ? ? ? ? ? ? ?}
? ? ? ? ? ?}
? ? ? ?}
? ?}
public void dfsTree(){
? ? ? ?if (root == null) {
? ? ? ? ? ?return;
? ? ? ?}
? ? ? ?Stack<Node> stack = new Stack<>();
? ? ? ?stack.add(root);
? ? ? ?while (!stack.isEmpty()) {
? ? ? ? ? ?Node tmpNode = stack.peek();
? ? ? ? ? ?System.out.println(stack.pop().value);
? ? ? ? ? ?if (tmpNode.children!=null){
? ? ? ? ? ?for (int i = tmpNode.children.size() -1 ; i >= 0 ; i--) {
? ? ? ? ? ? ? ? ? ?stack.add(tmpNode.children.get(i));
? ? ? ? ? ?}
? ? ? ? ? ?}
? ? ? ?}
? ?}
private class?Node ?{
? ?public int?value?;
? ?public?ArrayList<Node>?children;
? ?public?Node?(?int?value ) {
? ? ? ?this?.?value?= value?;
? ? ? ?children=null;
? ?}
}
private Node root ?;