본문 바로가기
알고리즘

[LeetCode] 104. Maximum Depth of Binary Tree (golang)

by 참새는 짹짹 2021. 6. 7.

문제


Maximum Depth of Binary Tree - LeetCode
Level up your coding skills and quickly land a job. This is the best place to expand your knowledge and get prepared for your next interview.
https://leetcode.com/problems/maximum-depth-of-binary-tree/
  • 이진 트리에서 최대 깊이 구하기

구현


  • 모든 가지를 탐색하여 깊이를 갱신 ( N )

시간 복잡도
  • O(N)

  • 코드
    /**
     * Definition for a binary tree node.
     * type TreeNode struct {
     *     Val int
     *     Left *TreeNode
     *     Right *TreeNode
     * }
     */
    func maxDepth(root *TreeNode) int {
        maxDepth := 0
        searchTree(root, 1, &maxDepth)
        return maxDepth
    }
    
    func searchTree(node *TreeNode, depth int, maxDepth *int) {
        if node == nil {
            return
        }
        if depth > *maxDepth {
            *maxDepth = depth
        }
        searchTree(node.Left, depth+1, maxDepth)
        searchTree(node.Right, depth+1, maxDepth)
    }

댓글