자바_이진검색트리(Binary Search Trees)

2019. 4. 18. 16:11알고리즘문제/Hackerrank

이진트리에 들어갈 숫자들의 갯수와 그 숫자를 입력받아 이진검색트리에 담고(insert

이진검색트리의 깊이를 출력(getHeight)하는 코드입니다. 

 

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){
        if(root == null) return -1;

        int leftDepth = getHeight(root.left);
        int rightDepth = getHeight(root.right);
        
        return Math.max(leftDepth,rightDepth)+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);
    }
}

'알고리즘문제 > Hackerrank' 카테고리의 다른 글

Minimum Operation  (0) 2019.04.03
자바 Pattern 클래스  (0) 2019.04.01
자바_정규표현식(matches, pattern)  (0) 2019.04.01
자바 SortedSet, TreeSet  (0) 2019.03.29
자바(Java)_Arrays.sort 메소드 활용  (0) 2019.03.27