Problem
Solution
Time Complexity
O(N)
Space Complexity
O(1)
# Definition for a binary tree node.
# class TreeNode(object):
# def __init__(self, x):
# self.val = x
# self.left = None
# self.right = None
class Solution(object):
def lowestCommonAncestor(self, root, p, q):
"""
:type root: TreeNode
:type p: TreeNode
:type q: TreeNode
:rtype: TreeNode
"""
# If p and q are on the same subtree of the current node,
# update ancester to its child node
# If they are on different subtree, current node is the final result
# If current node is updated to child node, and that node is equal to p or q, p or q is the result
if not root:
return root
ancester = root
curr = root
while True:
if p.val < curr.val and q.val < curr.val:
curr = curr.left
ancester = curr
elif p.val > curr.val and q.val > curr.val:
curr = curr.right
ancester = curr
else:
return curr
'CODE > Algorithms & Data Structures' 카테고리의 다른 글
[LeetCode] Construct Binary Tree from Preorder and Inorder Traversal (0) | 2021.10.29 |
---|---|
[LeetCode] Clone Graph (0) | 2021.10.27 |
[LeetCode] Populating Next Right Pointers in Each Node II (0) | 2021.10.24 |
[LeetCode] Binary Tree Level Order Traversal (0) | 2021.10.22 |
[LeetCode] Binary Tree Inorder Traversal (0) | 2021.10.21 |