[백준](트리) - 전위, 중위, 후위 순회

2855 단어 algorithmalgorithm

https://www.acmicpc.net/problem/1991

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.util.ArrayList;
import java.util.StringTokenizer;



class TrNode {
	public char data;
	public TrNode left;
	public TrNode right;
	
	public TrNode(char data) {
		this.data = data;
	}
}


public class TreeTraversal {

	public static void preorder(TrNode node) {
		if(node != null) {
			System.out.print(node.data);
			preorder(node.left);
			preorder(node.right);
		}
	}
	
	public static void inorder(TrNode node) {
		if(node != null) {
			inorder(node.left);
			System.out.print(node.data);
			inorder(node.right);
		}
	}
	
	public static void postorder(TrNode node) {
		if(node != null) {
			postorder(node.left);
			postorder(node.right);
			System.out.print(node.data);
		}
	}
	
	public static void createNode(TrNode node, char data, char left, char right) {
		if(node == null) {
			return;
		}else if(node.data == data ) {
			
			if(left != '.') {
				node.left = new TrNode(left);
			}
			if(right != '.') {
				node.right = new TrNode(right);
			}
		} else {
			createNode(node.left, data, left, right);
			createNode(node.right, data, left, right);			
		}
		
	}
	
	public static void main(String[] args) throws IOException {

//		BufferedReader br = new BufferedReader(new InputStreamReader(new FileInputStream(new File("src/tree_traversal.txt"))));
		BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
		
		StringTokenizer st = new StringTokenizer(br.readLine());
		
		int n = Integer.parseInt(st.nextToken());
		
		ArrayList<ArrayList<Integer>> ar = new ArrayList<ArrayList<Integer>>();
		for(int i=0; i<n; i++) {
			ar.add(new ArrayList<Integer>());
		}
		
		TrNode root = new TrNode('A');
		
		for(int i=0; i<n; i++) {
			st = new StringTokenizer(br.readLine());
			char data = st.nextToken().charAt(0);
			char left = st.nextToken().charAt(0);
			char right = st.nextToken().charAt(0);				
			
			createNode(root, data, left, right);
		}
		
		
		preorder(root);
		System.out.println();
		inorder(root);
		System.out.println();
		postorder(root);
		
	}

}

좋은 웹페이지 즐겨찾기