# Arup Guha
# 6/13/2017
# Python Turtle Program that draws a complete binary tree (horizontal)

import turtle
import math

# Movement constants for segments of the binary tree.
DX = 50
MAXDY = 100

# Returns the distance between (x1, y1) and (x2, y2)
def dist(x1,y1,x2,y2):
    return math.sqrt((x2-x1)**2 + (y2-y1)**2)

# Draws a line segment between (x1, y1) and (x2, y2)
def drawlineseg(x1,y1,x2,y2):

    # To be safe pick the pen up and move to the starting point.
    turtle.penup()
    turtle.setpos(x1,y1)
    
    # Figure out our direction of movement and go in that direction.
    # Note that atan2 returns in radians 
    angle = math.atan2(y2-y1,x2-x1)
    turtle.radians()
    turtle.setheading(angle)

    # Put the pen down and move forward
    turtle.pendown()
    turtle.forward(int(dist(x1,y1,x2,y2)))
    turtle.penup()

def drawtree(x, y, depth, mydx, mydy):

    # Leaf node - we stop.
    if depth == 0:
        return

    # Draw both branches from the root.
    drawlineseg(x, y, x+mydx, y-mydy)
    drawlineseg(x, y, x+mydx, y+mydy)

    # Recursively draw the left and right subtrees. We divide the width(dy)
    # by 2 since we have to fit twice as many nodes in the same space.
    drawtree(x+mydx, y-mydy, depth-1, mydx, mydy//2)
    drawtree(x+mydx, y+mydy, depth-1, mydx, mydy//2)

def main():
    drawtree(-200, 0, 5, DX, MAXDY)

main()
