iT邦幫忙

2022 iThome 鐵人賽

0
自我挑戰組

LeetCode Top 100 Liked系列 第 44

[Day 44] Lowest Common Ancestor of a Binary Tree (Medium)

  • 分享至 

  • xImage
  •  

236. Lowest Common Ancestor of a Binary Tree

Solution 1: DFS

class Solution:
    def lowestCommonAncestor(self, root: 'TreeNode', p: 'TreeNode', q: 'TreeNode') -> 'TreeNode':
        if not root or (root == p or root == q):
            return root
        
        lcaOfLft = self.lowestCommonAncestor(root.left, p, q)
        lcaOfRht = self.lowestCommonAncestor(root.right, p, q)
        if lcaOfLft and lcaOfRht:
            return root
        elif lcaOfLft is None:
            return lcaOfRht
        else: # lcaOfRht is None:
            return lcaOfLft

Time Complexity: O(N)
Space Complexity: O(N) // Worst case happened when tree is skewed

Reference

https://leetcode.com/problems/lowest-common-ancestor-of-a-binary-tree/discuss/1405170/4-STEPS-SOLUTION-or-Easy-Heavily-EXPLAINED-with-COMPLEXITIES
https://leetcode.com/problems/lowest-common-ancestor-of-a-binary-tree/discuss/152682/Python-simple-recursive-solution-with-detailed-explanation


上一篇
[Day 43] Sort List (Medium)
下一篇
[Day 45] Reverse Nodes in k-Group (Hard)
系列文
LeetCode Top 100 Liked77
圖片
  直播研討會
圖片
{{ item.channelVendor }} {{ item.webinarstarted }} |
{{ formatDate(item.duration) }}
直播中

尚未有邦友留言

立即登入留言