물음표 살인마의 개발블로그

알고리즘 문제/Leetcode

543. Diameter of Binary Tree

BEstyle 2023. 1. 21. 05:54

Given the root of a binary tree, return the length of the diameter of the tree.

The diameter of a binary tree is the length of the longest path between any two nodes in a tree. This path may or may not pass through the root.

The length of a path between two nodes is represented by the number of edges between them.

 

Example 1:

Input: root = [1,2,3,4,5]
Output: 3
Explanation: 3 is the length of the path [4,2,1,3] or [5,2,1,3].

Example 2:

Input: root = [1,2]
Output: 1

 

Constraints:

  • The number of nodes in the tree is in the range [1, 104].
  • -100 <= Node.val <= 100

# https://www.acmicpc.net/problem/

'''
1. 아이디어 :
    1) DFS로 풀 수 있다. 각 노드의 차일드의 height를 저장하고, 해당 노드는 두 차일드 +1개의 height이고,
    최대 길이는 두 차일드의 height +2 가된다. max를 이용하여 최대값 갱신한다.
2. 시간복잡도 :
    1) O(n)
3. 자료구조 :
    1) DFS
'''


# Definition for a binary tree node.
# class TreeNode:
#     def __init__(self, val=0, left=None, right=None):
#         self.val = val
#         self.left = left
#         self.right = right
class Solution:
    def diameterOfBinaryTree(self, root: Optional[TreeNode]) -> int:
        maxDiameter=[0]

        def dfs(node):
            if not node:
                return -1
            left = dfs(node.left)
            right = dfs(node.right)
            maxDiameter[0] = max(maxDiameter[0], 2+left+right)

            height = 1 + max(left,right)
            return height

        dfs(root)
        return maxDiameter[0]

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

104. Maximum Depth of Binary Tree  (0) 2023.01.21
226. Invert Binary Tree  (0) 2023.01.21
101. Symmetric Tree  (0) 2023.01.21
872. Leaf-Similar Trees  (0) 2023.01.21
938. Range Sum of BST  (0) 2023.01.21