Skip to content

Instantly share code, notes, and snippets.

@liondancer
liondancer / lowest_common_ancestor_binary_tree.py
Created January 3, 2017 19:55
Lowest Common Ancestor of a Binary Tree
def lowestCommonAncestor(self, root, p, q):
# O(n) runtime and constant space
if root in (None, p, q): return root
left = lowestCommonAncestor(root.left, p, q)
right = lowestCommonAncestor(root.right, p, q)
if left and right:
return root
if left:
return left
return right
def lowestCommonAncestor(root, p, q):
"""
:type root: TreeNode
:type p: TreeNode
:type q: TreeNode
:rtype: TreeNode
"""
if max(p.val, q.val) < root.val:
return lowestCommonAncestor(root.left, p, q)
elif min(p.val, q.val) > root.val:
@liondancer
liondancer / levelorderprint.py
Created January 4, 2017 00:55
Print by level order
def levelOrder(root):
"""
:type root: TreeNode
:rtype: List[List[int]]
"""
if root:
queue = [root]
res = []
while queue:
tmp = []
def isValid(s):
"""
:type s: str
:rtype: bool
"""
if s:
if len(s) == 1:
return False
stack = []
d = {'[': ']', '(': ')', '{': '}'}
import sys
def isValidBST(root, max=sys.maxint, min=-sys.maxint):
"""
:type root: TreeNode
:rtype: bool
"""
if root is None:
return True
return root.val < max and root.val > min and isValidBST(root.left, max=root.val, min=min) and isValidBST(root.right, max=max, min=root.val)
def maxDepth(root):
"""
:type root: TreeNode
:rtype: int
"""
if root is None:
return 0
return max(maxDepth(root.left), maxDepth(root.right)) + 1
def minDepth(root):
"""
:type root: TreeNode
:rtype: int
"""
if root is None:
return 0
elif root.left is None:
return minDepth(root.right) + 1
elif root.right is None:
def spiralOrder(matrix):
"""
:type matrix: List[List[int]]
:rtype: List[int]
"""
if len(matrix) == 0:
return []
if len(matrix) == 1:
return matrix[0]
def canFinish(numCourses, prerequisites):
"""
:type numCourses: int
:type prerequisites: List[List[int]]
:rtype: bool
"""
if prerequisites:
# create graph
courses = {}
def findOrder(numCourses, prerequisites):
"""
:type numCourses: int
:type prerequisites: List[List[int]]
:rtype: List[int]
"""
if prerequisites:
d = {}
for i in range(numCourses):
d[i] = set()