본문 바로가기
1 Day 1 Algorithms

[2019.01.14] BST Level-Order Traversal

by 곰돌찌 2019. 1. 14.

Problem


Objective 
Today, we're going further with Binary Search Trees. Check out the Tutorial tab for learning materials and an instructional video!

Task 
A level-order traversal, also known as a breadth-first search, visits each level of a tree's nodes from left to right, top to bottom. You are given a pointer, , pointing to the root of a binary search tree. Complete the levelOrder function provided in your editor so that it prints the level-order traversal of the binary search tree.

Hint: You'll find a queue helpful in completing this challenge.

Input Format

The locked stub code in your editor reads the following inputs and assembles them into a BST: 
The first line contains an integer,  (the number of test cases). 
The  subsequent lines each contain an integer, , denoting the value of an element that must be added to the BST.

Output Format

Print the  value of each node in the tree's level-order traversal as a single line of  space-separated integers.

Sample Input

6
3
5
4
7
2
1

Sample Output

3 2 5 1 4 7 

Explanation

The input forms the following binary search tree: 

We traverse each level of the tree from the root downward, and we process the nodes at each level from left to right. The resulting level-order traversal is , and we print these data values as a single line of space-separated integers.


How I solved the problem


# Binary Search Tree와 Queue를 함께 써서 풀어보는 문제..!
# Node와 Binary Search Tree의 개념을 한 번 더 되짚어보기


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
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
import java.util.*;
import java.io.*;
class Node{
    Node left,right;
    int data;
    Node(int data){
        this.data=data;
        left=right=null;
    }
}
class Solution{
 
static void levelOrder(Node root){ //binary search tree와 queue를 혼합한 문제
      //Write your code here
      Queue<Node> queue = new LinkedList();
      //Queue이기 때문에 first in, first out의 개념이 들어가 있음
      queue.add(root);
      
      String result = "";
 
      while (!queue.isEmpty()) {
          Node current = queue.remove();
          //먼저 현재 current node의 데이터를 result에 넣음
          result += " " + current.data;
          
          //왼쪽을 먼저 읽기 때문에 왼쪽이 있는지 확인한 후 add
          if (current.left != null) {
              queue.add(current.left);
          }
          
          //다음에 오른쪽이 있는지 확인한 후 add
          if (current.right != null) {
              queue.add(current.right);
          }
      }
 
      System.out.println(result.substring(1));
}
 
public static Node insert(Node root,int data){
        if(root==null){
            return new Node(data);
        }
        else{
            Node cur;
            if(data<=root.data){
                cur=insert(root.left,data);
                root.left=cur;
            }
            else{
                cur=insert(root.right,data);
                root.right=cur;
            }
            return root;
        }
    }
    public static void main(String args[]){
            Scanner sc=new Scanner(System.in);
            int T=sc.nextInt();
            Node root=null;
            while(T-->0){
                int data=sc.nextInt();
                root=insert(root,data);
            }
            levelOrder(root);
        }    
}
cs


[출처 : https://www.hackerrank.com ]


'1 Day 1 Algorithms' 카테고리의 다른 글

[2019.01.16] Running Time and Complexity  (0) 2019.01.16
[2019.01.15] More Linked Lists  (0) 2019.01.15
[2019.01.11] Binary Search Trees  (0) 2019.01.11
[2019.01.10] Generics  (0) 2019.01.10
[2019.01.09] Sorting  (0) 2019.01.09

댓글