Notice
Recent Posts
Recent Comments
Link
일 | 월 | 화 | 수 | 목 | 금 | 토 |
---|---|---|---|---|---|---|
1 | 2 | 3 | 4 | |||
5 | 6 | 7 | 8 | 9 | 10 | 11 |
12 | 13 | 14 | 15 | 16 | 17 | 18 |
19 | 20 | 21 | 22 | 23 | 24 | 25 |
26 | 27 | 28 | 29 | 30 | 31 |
Tags
- 코틀린
- 배열
- 분할정복
- 동적계획법
- Android
- 그래프
- 안드로이드
- 세그먼트트리
- 완전탐색
- 문자열다루기
- GIT
- 알고리즘
- BFS
- 백준
- 문자열
- 프로그래머스
- 이분탐색
- 스택
- BOJ
- 자바
- 코딩
- activity
- dfs
- component
- 운영체제
- 카카오블라인드
- 다이나믹프로그래밍
- 생명주기
- 코딩테스트
- 트리
Archives
- Today
- Total
HS_development_log
트리(Tree) / Java 본문
반응형
자바를 이용한 트리의 기본구조 입니다.
이진트리의 구조가 아닙니다.
하나의 노드가 여러개의 자식노드를 가질 수 있도록 코딩했습니다.
소스코드
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 | import java.util.*; public class Tree { public static void main(String[] args) { Node root = new Node("1"); Node n2 = new Node("2"); Node n3 = new Node("3"); Node n4 = new Node("4"); Node n5 = new Node("5"); root.add(n2); root.add(n3); root.add(n4); n3.add(n5); } } class Node{ Node parent; String data; ArrayList<Node> children; Node(String data){ this.parent = null; this.data = data; children = new ArrayList<Node>(); } public void add(Node child) { child.parent = this; this.children.add(child); } public void print() { if(this.parent==null) { /* 최상위 루트 노드일경우에만 본인 출력 */ System.out.println(this.data); } if(this.children.size()!=0) { for(int i=0;i<this.children.size();i++) { /* 자식노드가 있을경우 모든 자식노드를 출력하고 */ System.out.print(this.children.get(i).data+" "); } System.out.println(); for(int i=0;i<this.children.size();i++) { /* 자식노드 마다 똑같이 재귀적으로 print함수 호출 */ this.children.get(i).print(); } } } } | cs |
출력
표현그림
반응형
'Algorithm-이론' 카테고리의 다른 글
알고리즘 실용 - Wrapper 클래스 메서드 활용 (0) | 2020.08.12 |
---|---|
자바 Collections 라이브러리의 시간 복잡도 (0) | 2020.02.01 |
가장 큰 증가하는 부분 수열(LIS) (0) | 2020.01.17 |
알고리즘 - 수학 (0) | 2020.01.15 |
세그먼트 트리(Segment Tree) / Java (0) | 2020.01.13 |