# Size and Height of a Binary Tree

```class BinaryTree:
def __init__(self, root):
self.root = root
self.leftChild = None
self.rightChild = None

def setRoot(self, root):
self.root = root

def getRoot(self):
return self.root

def getLeftChild(self):
return self.leftChild

def getRightChild(self):
return self.rightChild

def insertLeftChild(self, newNode):
if self.leftChild == None:
self.leftChild = BinaryTree(newNode)
else:
t = BinaryTree(newNode)
t.leftChild = self.leftChild
self.leftChild = t

def insertRightChild(self, newNode):
if self.rightChild == None:
self.rightChild = BinaryTree(newNode)
else:
t = BinaryTree(newNode)
t.rightChild = self.rightChild
self.rightChild = t

'''recursive process for finding height of a binary tree'''
def height(tree):
if tree == None:
return 0
else:
return max(height(tree.leftChild),height(tree.rightChild)) + 1

'''iterative process for finding height of a binary tree'''
def heightIterative(tree):
height = 0
if tree == None:
return 0

queue = []
queue.append(tree)
queue.append("NULL")

while ( queue != []):
root = queue.pop(0)
if root == "NULL":
if queue != []:
queue.append("NULL")
height += 1
else:
if root.getLeftChild():
queue.append(root.getLeftChild())
if root.getRightChild():
queue.append(root.getRightChild())

return height

'''recursive process for finding size of a binary tree'''
def size(tree):
if tree == None:
return 0
else:
return size(tree.getLeftChild()) + 1+ size(tree.getRightChild())

if __name__ == "__main__":

r = BinaryTree(5)
r.insertLeftChild(6)
r.insertRightChild(7)
r.leftChild.insertLeftChild(12)
r.leftChild.insertRightChild(54)
r.rightChild.insertRightChild(63)

print "Height of the tree is:", height(r)
print "\n\n"

print "size of the tree is:", size(r)
print "\n\n"

print "height of the tree is:", heightIterative(r)
print "\n\n"

```

## 4 thoughts on “Size and Height of a Binary Tree”

1. hey there and thank you for your info – I have definitely picked
up something new from right here. I did however expertise several
technical points using this web site, since I experienced to reload the web
site many times previous to I could get it to load correctly.