ZhongKuo0228 / study

0 stars 0 forks source link

236. Lowest Common Ancestor of a Binary Tree #95

Open fockspaces opened 11 months ago

fockspaces commented 11 months ago

對 p, q 來說,只會有兩種情形:

  1. p, q 在同側 將最早發現的 p or q 往上傳,其本身即為另一個節點的 lowest ancestor
  2. p, q 在不同側 我們只要將 p, q 找到之後往上傳即可,當第一個發現 p, q 在左右兩邊的節點,即為 lowest ancestor
# 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':
        if not root:
            return None
        if root == p or root == q:
            return root
        left = self.lowestCommonAncestor(root.left, p, q)
        right = self.lowestCommonAncestor(root.right, p, q)
        if left and right:
            return root
        return left if left else right
fockspaces commented 11 months ago

GPT improve: 將 if 邏輯簡化

# 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':
        if not root or root == p or root == q:
            return root
        left = self.lowestCommonAncestor(root.left, p, q)
        right = self.lowestCommonAncestor(root.right, p, q)
        if left and right:
            return root
        return left if left else right