본문 바로가기
Algorithm

[Algorithm] Maximum Depth of Binary Tree

by NOHCODING 2023. 6. 15.
반응형

01. 문제내용

https://leetcode.com/problems/maximum-depth-of-binary-tree/

 

Maximum Depth of Binary Tree - LeetCode

Can you solve this real interview question? Maximum Depth of Binary Tree - Given the root of a binary tree, return its maximum depth. A binary tree's maximum depth is the number of nodes along the longest path from the root node down to the farthest leaf

leetcode.com

Given the root of a binary tree, return its maximum depth.

A binary tree's maximum depth is the number of nodes along the longest path from the root node down to the farthest leaf node.

 

 

02. 문제 풀이로 배운점

이진탐색 트리를 파이썬으로 구현한적이 있었다. node 클래스를 생성하고 tree 클래스를 생성하여 node의 객체를 tree안에 선언하여 사용했던 기억이 있는데, 이번 문제를 풀며 TreeNode 코드를 보고 '유레카!'라는 느낌이 들었다. 

 

리트코드에서 기본적으로 제공하는 TreeNode는 아래와 같다. TreeNode 객체를 하나로 사용하는 것이 정말 효율적이고 이것이야말로 객체지향!!!!이라는 느낌!🥲 정말 아직도 멀었다...허허

public class TreeNode{
	int val;
    	TreeNode left;
    	TreeNode rigth;
    
        TreeNode(){}

        TreeNode(int val){
            this.val = val;
        }

        TreeNode(int val, TreeNode left, TreeNode right){
            this.val = val;
            this.left = left;
            this.right = right;
        }
}

 

이번 문제는 트리의 Deth를 구하는 것이라 DFS를 사용하여 문제를 풀이해 보았다!

풀이하는 모든사람이 Runtime 0을 기록!

 

03. 문제 풀이 코드

class Solution {

    public int maxDepth(TreeNode root) {

        if(root == null){
            return 0;
        }

        int left = maxDepth(root.left);
        int right = maxDepth(root.right);

        return Math.max(left, right) + 1;

    }

}

 

 

 

반응형

댓글