Tuesday, March 25, 2014

Implement a function to check if a tree is balanced. For the purposes of this question, a balanced tree is defined to be a tree such that no two leaf nodes differ in distance from the root by more than one.

__author__ = 'nitin'

class BinaryTree:
    def __init__(self,rootObj):
        self.key = rootObj
        self.leftChild = None
        self.rightChild = None

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

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

    def getRightChild(self):
        return self.rightChild

    def getLeftChild(self):
        return self.leftChild

    def setRootVal(self,obj):
        self.key = obj

    def getRootVal(self):
        return self.key

def max_depth(root):
    if root is None:
        return 0
    else:
        return 1 + max(max_depth(root.getLeftChild()),max_depth(root.getRightChild()))

def min_depth(root):
    if root is None:
        return 0
    else:
        return 1 + min(min_depth(root.getLeftChild()),min_depth(root.getRightChild()))

def is_balanced(root):
    result=max_depth(root) - min_depth(root)
    if result>1:
        return False
    else:
        return True

r = BinaryTree('a')
r.insertLeft('b')
r.insertRight('c')
r.insertLeft('d')
r.insertLeft('e')
r.insertLeft('f')
r.insertLeft('g')
r.insertLeft('h')

print is_balanced(r)

No comments:

My Profile

My photo
can be reached at 09916017317