본문 바로가기
코드

Maximum Depth of Binary Tree

by ehei 2019. 10. 24.

2진 트리의 깊이를 재는 문제. 깊이 우선 탐색을 쓰면 간단히 풀린다

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

 

# Definition for a binary tree node.
# class TreeNode:
#     def __init__(self, x):
#         self.val = x
#         self.left = None
#         self.right = None

class Solution:
    def maxDepth(self, root: TreeNode) -> int:
        if root is None:
            return 0
        else:
            return self.__maxDepth( root, 1 )
    
    
    def __maxDepth(self, root, count) -> int:
        if root.left is not None:
            leftDepth = self.__maxDepth(root.left, count + 1 )
        else:
            leftDepth = count
            
        if root.right is not None:
            rightDepth = self.__maxDepth(root.right, count + 1 )
        else:
            rightDepth = count
        
        return max( leftDepth, rightDepth, count )

'코드' 카테고리의 다른 글

Merge Two Sorted Lists  (0) 2019.10.24
Pow(x, n)  (0) 2019.10.24
Climbing Stairs  (0) 2019.10.24
Fibonacci Number  (0) 2019.10.24
Reverse Linked List  (0) 2019.10.24