leecode 깊이 우선 검색 DFS

10680 단어 Leecode

104 두 갈래 나무의 최대 깊이

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

class Solution(object):
    def maxDepth(self, root):
        """
        :type root: TreeNode
        :rtype: int
        """
        if not root: return 0
        q = [root]
        stash = []
        ans = 0
        while q:
            r = q.pop()
            if r.left:
                stash.append(r.left)
            if r.right:
                stash.append(r.right)
            if len(q) == 0:
                q = stash
                ans += 1
                stash = []
        return ans

1123 가장 깊은 잎 노드의 최근 공공 조상


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

class Solution(object):
    def lcaDeepestLeaves(self, root):
        """
        :type root: TreeNode
        :rtype: TreeNode
        """
        def dfs(root):
            if not root:
                return None, 0
            lr, ld = dfs(root.left)
            rr, rd = dfs(root.right)
            if ld > rd:
                return lr, ld + 1
            elif ld < rd:
                return rr, rd + 1
            else:
                return root, ld + 1
        ans, h = dfs(root)
        return ans

865 모든 가장 깊은 노드를 가진 최소 하위 트리

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

class Solution(object):
    def subtreeWithAllDeepest(self, root):
        """
        :type root: TreeNode
        :rtype: TreeNode
        """
        def f(root):
            if not root:
                return None, 0
            l, r = f(root.left), f(root.right)
            if l[1] > r[1]:
                return l[0], l[1] + 1
            elif l[1] < r[1]:
                return r[0], r[1] + 1
            else:
                return root, r[1] + 1
        return f(root)[0]

좋은 웹페이지 즐겨찾기