파비의 매일매일 공부기록

Today's Challenge 본문

Problem Solving/LeetCode

Today's Challenge

fabichoi 2022. 7. 26. 23:45

https://leetcode.com/problems/lowest-common-ancestor-of-a-binary-tree/

 

Lowest Common Ancestor of a 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.

leetcode.com

오랫만에 트리 구조의 문제

class Solution:
    def lowestCommonAncestor(self, root: 'TreeNode', p: 'TreeNode', q: 'TreeNode') -> 'TreeNode':
        stack = [root]
        parent = {root: None}
        
        while p not in parent or q not in parent:

            node = stack.pop()
            
            if node.left:
                parent[node.left] = node
                stack.append(node.left)
            if node.right:
                parent[node.right] = node
                stack.append(node.right)

        ancestors = set()
        
        while p:
            ancestors.add(p)
            p = parent[p]
        
        while q not in ancestors:
            q = parent[q]
        return q
반응형

'Problem Solving > LeetCode' 카테고리의 다른 글

Today's Challenge  (0) 2022.07.28
Today's Challenge  (0) 2022.07.27
Today's Challenge  (0) 2022.07.25
Today's Challenge  (0) 2022.07.24
Today's Challenge  (0) 2022.07.23
Comments