[알고리즘]_[LeetCode]- 104. Maximum Depth of Binary Tree

SAPCO·2022년 7월 27일
0

- [Algorithm]

목록 보기
10/13
post-custom-banner

📍 1. 문제

LeetCode - 104. Maximum Depth of Binary Tree

📍 2. 풀이

📌 2-1. 풀이 (reculsive)

(1) 방법

재귀로 풀이.

위 트리를 재귀형태로 풀면 다음과 같은 순서.


maxDepth(3)
LD = maxDepth(9) = 1

	maxDepth(9) = 1
		LD = maxDepth(null) = 0
			
			maxDepth(null)
				return 0;

		RD = maxDepth(null)

			maxDepth(null)
				return 0;

		return 1 + Math.max(LD 0 , RD 0) = 1

RD = maxDepth(20) = 2
	
	maxDepth(20) = 2
		LD = maxDepth(15) = 1
		
		maxDepth(15) = 1
			LD = maxDepth(null) = 0
			RD = maxDepth(null) = 0
			return 1 + Math.max(LD 0, RD 0);

		RD = maxDepth(7) = 1

			maxDepth(7) = 1
			LD = maxDepth(null) = 0
			RD = maxDepth(null) = 0
			return 1 + Math.max(LD 0 , RD 0);

		return 1 + Math.max(LD 1,RD 1) = 2
return 1 + Math.max(LD 1 , RD 2) = 3

(2) 코드

/**
 * Definition for a binary tree node.
 * public class TreeNode {
 *     int val;
 *     TreeNode left;
 *     TreeNode right;
 *     TreeNode() {}
 *     TreeNode(int val) { this.val = val; }
 *     TreeNode(int val, TreeNode left, TreeNode right) {
 *         this.val = val;
 *         this.left = left;
 *         this.right = right;
 *     }
 * }
 */
class Solution {
    public int maxDepth(TreeNode root) {
        if(root == null) return 0;
        
        int lD = maxDepth(root.left);
        int rD = maxDepth(root.right);
        
        return 1 + Math.max(lD, rD);
    }
}

(3) 결과

📍 3. 결론

iteration으로도 풀어봐야지

profile
SAP CO
post-custom-banner

0개의 댓글