236. Lowest Common Ancestor of a Binary Tree - LeetCode Solution


Tree DFS BFS

Python Code:

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

class Solution:
    def lowestCommonAncestor(self, root: 'TreeNode', p: 'TreeNode', q: 'TreeNode') -> 'TreeNode':
        def trav(root):
            if not root:
                return [False, False, None]
            
            a = trav(root.left)
            b =  trav(root.right)
            if a[-1] != None:
                return a
            if b[-1] != None:
                return b
            arr = [False, False, None]
            if root == p:
                arr[0] = True
            if root == q:
                arr[1] = True
            arr[0] = arr[0] or a[0] or b[0]
            arr[1] = arr[1] or a[1] or b[1]
            if arr[0] and arr[1]:
                arr[2] = root
                return arr
            return arr
        return trav(root)[2]


Comments

Submit
0 Comments
More Questions

152C - Pocket Book
1681D - Required Length
1725D - Deducing Sortability
1501A - Alexey and Train
721B - Passwords
1263D - Secret Passwords
1371B - Magical Calendar
1726E - Almost Perfect
1360C - Similar Pairs
900A - Find Extra One
1093D - Beautiful Graph
748A - Santa Claus and a Place in a Class
1511B - GCD Length
676B - Pyramid of Glasses
597A - Divisibility
1632A - ABC
1619D - New Year's Problem
242B - Big Segment
938A - Word Correction
159C - String Manipulation 10
258A - Little Elephant and Bits
1536C - Diluc and Kaeya
1428C - ABBB
1557A - Ezzat and Two Subsequences
255A - Greg's Workout
1059A - Cashier
1389C - Good String
1561A - Simply Strange Sort
1337B - Kana and Dragon Quest game
137C - History