티스토리 뷰

반응형

 

 

 

지난 포스팅의 자바 Day22 강좌 리뷰에 이어

이번 포스팅에서는 Day 22 자바 코드 리뷰를 진행해보자.

 

Day 22

 

 


 

이번 문제는 필자가

이전 강의 포스팅에서 꼼꼼하게 이해했던(!!)

cardinality() 부분이 문제로 출제되었다!!!

(강의 들으면서 몰랐었던 부분 그냥 넘어가지 않고

꼼꼼히 추가 공부 잘했다고 생각했다. 뿌듯😆)

 

혹시나 하고 이전 포스팅의 링크를 걸어둘테니

안본 사람은 정말 꼭 보길 추천한다!!

(이전 포스팅 보러가기)

 

 

또한 이번 문제에서

필자가 caldinality() 구하는 공식은 알겠는데

그거 조금만 응용하면 height 찾을 수 있겠는데

코드를 어떻게 작성할지 몰라

compile error를 냈던 코드가 있다.

 

그 코드 또한 살펴보자.

 

그래서 먼저 compile 에러가 난 코드부터 살펴보도록 하겠다.

 


 

 

import java.util.*;
import java.io.*;
class Node{
    Node left,right;
    int data;
    Node(int data){
        this.data=data;
        left=right=null;
    }
}
class Solution{
    public int getHeight(Node root){
      //Write your code here
      int leftHeight = 0;
      int rightHeight = 0;
      
      if(root.left != null) {
          leftHeight = root.left.getHeight(root.left);
      } 
      if(root.right != null) {
          rightHeight = root.right.getHeight(root.right);
      }
      return 1 + Math.max(leftHeight, rightHeight);
    }
    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);
        }
        int height=getHeight(root);
        System.out.println(height);
    }
}

 

 

이전 포스팅에서 설명했듯이

getHeight()를 구하려면

if(root.left(right) != null) 이면

또 한번 재귀로 getHeight() 함수를 불러야하는데

leftHeight = root.left.getHeight(root.left); 코드가 에러가 나는 것이었다.

 

처음 필자는 getHeight(Node root)에서

Node 타입이면 다 되는 것 아닌가라고 생각했는데

root.left도 어쨌든 Node 타입이니 가능하지 않은가 라고 생각했는데

 

root.left.getHeight(root.left);를 사용하려면

public int getHeight(Node left) {} 메서드를 만들어야했다.

 

 

 

따라서 인터넷의 도움을 받아

다음의 코드를 작성할 수 있었다.

(도움 받은 출처 - 글자 클릭 시 이동)

 

이제 최종 코드를 확인해보자.

 


 

import java.util.*;
import java.io.*;

class Node{
    Node left,right;
    int data;
    Node(int data){
        this.data=data;
        left=right=null;
    }
}
class Solution{
    public static int getHeight(Node root){
        //Write your code here
        if(root == null) return -1;
        return Math.max(getHeight(root.left), getHeight(root.right)) + 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);
        }
        int height=getHeight(root);
        System.out.println(height);
    }
}

 

 

 

우리가 작성해야할 부분인

getHeight(Node root) 메서드를

자세히 보면

public static int getHeight(Node root){
    //Write your code here
    if(root == null) return -1;
    return Math.max(getHeight(root.left), getHeight(root.right)) + 1;
}

 

root==null일 때는 return -1을 해주고

root가 null이 아닐 때는 getHeight(root.left)와 getHeight(root.right) 중

큰 값에 +1(root)을 return해주면 되었다.

 

딱히 이해하는데 어려운 알고리즘은 아니었으나

타입 에러로 인한 문제는 필자에게 아직 조금 헷갈린다.

 

추후에 복습해보아야겠다.

 

 

 


 

 

그럼 우리는 내일

Day 23 포스팅으로 다시 만나자.

오늘도 다들 즐거운 코딩하자. .😊

반응형