일 | 월 | 화 | 수 | 목 | 금 | 토 |
---|---|---|---|---|---|---|
1 | ||||||
2 | 3 | 4 | 5 | 6 | 7 | 8 |
9 | 10 | 11 | 12 | 13 | 14 | 15 |
16 | 17 | 18 | 19 | 20 | 21 | 22 |
23 | 24 | 25 | 26 | 27 | 28 |
Tags
- kaggle
- Generator
- 프로그래머스
- DWG
- Python
- Python Implementation
- Convert Sorted List to Binary Search Tree
- concurrency
- Regular Expression
- 컴퓨터의 구조
- 43. Multiply Strings
- data science
- Decorator
- 시바견
- 715. Range Module
- t1
- 운영체제
- shiba
- LeetCode
- Substring with Concatenation of All Words
- 315. Count of Smaller Numbers After Self
- Protocol
- 109. Convert Sorted List to Binary Search Tree
- Python Code
- 파이썬
- Class
- iterator
- attribute
- 밴픽
- 30. Substring with Concatenation of All Words
Archives
- Today
- Total
Scribbling
LeetCode: 236. Lowest Common Ancestor of a Binary Tree 본문
Computer Science/Coding Test
LeetCode: 236. Lowest Common Ancestor of a Binary Tree
focalpoint 2021. 12. 15. 22:43코드가 너무 복잡하다.
# 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':
self.ret = None
self.dfs(root, p, q)
return self.ret
def dfs(self, node, p, q):
if node == None:
return None
l = self.dfs(node.left, p, q) if node.left else None
r = self.dfs(node.right, p, q) if node.right else None
if (l == True) or (r == True):
return True
if node == p:
if l == q or r == q:
self.ret = node
return True
else:
return p
elif node == q:
if l == p or r == p:
self.ret = node
return True
else:
return q
elif (l == p and r == q) or (l == q and r == p):
self.ret = node
return True
elif l == p or l == q:
return l
elif r == p or r == q:
return r
return None
재귀적으로 아래와 같이 풀 수 있다.
# 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 root == p or root == q:
return root
left = right = None
if root.left:
left = self.lowestCommonAncestor(root.left, p, q)
if root.right:
right = self.lowestCommonAncestor(root.right, p, q)
if left and right:
return root
if left:
return left
return right
'Computer Science > Coding Test' 카테고리의 다른 글
LeetCode: 125. Valid Palindrome (0) | 2021.12.20 |
---|---|
LeetCode: 101. Symmetric Tree (0) | 2021.12.19 |
LeetCode: 230. Kth Smallest Element in a BST (0) | 2021.12.14 |
LeetCode: 968. Binary Tree Cameras (0) | 2021.12.13 |
LeetCode: 4. Median of Two Sorted Arrays (0) | 2021.12.12 |