Advertisement
bennyfromtheblock

236. Lowest Common Ancestor of a Binary Tree

Nov 2nd, 2021
83
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Python 0.97 KB | None | 0 0
  1. # TC: O(N)
  2. # SC: O(N), the height of the tree is how many recursion call stacks we incur. Worst case is N
  3.  
  4. # Definition for a binary tree node.
  5. # class TreeNode:
  6. #     def __init__(self, x):
  7. #         self.val = x
  8. #         self.left = None
  9. #         self.right = None
  10.  
  11. class Solution:
  12.     def lowestCommonAncestor(self, root: 'TreeNode', p: 'TreeNode', q: 'TreeNode') -> 'TreeNode':
  13.         res = None
  14.        
  15.         def dfs(root, p, q) -> bool:
  16.             nonlocal res
  17.             if not root:
  18.                 return False
  19.            
  20.             found_root = root == p or root == q
  21.             found_left = dfs(root.left, p, q)
  22.             found_right = dfs(root.right, p, q)
  23.            
  24.             if found_left or found_right:
  25.                 if (found_left and found_right) or found_root:
  26.                     res = root
  27.            
  28.             return found_root or found_left or found_right
  29.        
  30.         dfs(root, p, q)
  31.        
  32.         return res
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement