본문 바로가기
Develop/Algorithm

treeBFS - 깊이 우선 탐색 알고리즘

by jaeyoungb 2022. 10. 26.
import java.util.*;

public class Solution {
  public ArrayList<String> bfs(tree node) {
    Queue<tree> queue = new LinkedList<>();
    ArrayList<String> values = new ArrayList<>();
    queue.add(node);
    
    while(queue.size() > 0) {
      tree curNode = queue.poll();
      values.add(curNode.getValue());
      if(curNode.getChildrenNode() != null) {
        queue.addAll(curNode.getChildrenNode());
      }
    }
    return values;
  } 

  public static class tree {
    private String value;
    private ArrayList<tree> children;

    public tree(String data) {
      this.value = data;
      this.children = null;
    }

    public tree addChildNode(tree node) {
      if(children == null) children = new ArrayList<>();
      children.add(node);
      return children.get(children.size() - 1);
    }

    public String getValue() {      //현재 노드의 데이터를 반환
      return value;
    }

    public ArrayList<tree> getChildrenNode() {
      return children;
    }
  }
}