Skip to content

Instantly share code, notes, and snippets.

@jcchurch
Created October 28, 2013 06:30
Show Gist options
  • Save jcchurch/7192223 to your computer and use it in GitHub Desktop.
Save jcchurch/7192223 to your computer and use it in GitHub Desktop.
class Tree:
def __init__(self, x=0, l=None, r=None):
self.x = x
self.l = l
self.r = r
def visibleCountRecursive(root, maxthusfar):
visible = 0
visibleLeft = 0
visibleRight = 0
if root.x >= maxthusfar:
visible = 1
if root.l is not None:
visibleLeft = visibleCountRecursive(root.l, max(maxthusfar, root.x))
if root.r is not None:
visibleRight = visibleCountRecursive(root.r, max(maxthusfar, root.x))
return visible + visibleLeft + visibleRight
def solution(root):
return visibleCountRecursive(root, -1)
firstExample = Tree(5, Tree(3, Tree(20), Tree(21)), Tree(10, Tree(1), None))
secondExample = Tree(8, Tree(2, Tree(8), Tree(7)), Tree(6))
print solution(firstExample)
print solution(secondExample)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment