By perfectly balanced do you mean a complete tree? A full tree? Merely a height balanced or weight balanced tree? The algorithm is different for each. Typically what's meant is height balance, or what would be the desired end structure maintained an AVL tree.
A recursive algorithm presents itself immediately when you think about measuring the height of each subtree and comparing them:
is_balanced(tree)
balanced = true
height_diff = 0
if not empty(tree)
balanced = is_balanced(tree.left) and is_balanced(tree.right)
height_diff = abs(height(tree.left) - height(tree.right))
end if
return empty or (balanced and height_diff <= 1)
deceptikon
Challenge Accepted
3,499 posts since Jan 2012
Reputation Points: 822
Solved Threads: 481
Skill Endorsements: 58
Well, you could derive a solution directly from the wording of the definition. First count the number of nodes to get a value for n, then determine the depth of the tree so you know what the last level is, finally do a level order traversal and check at the end of each level whether the size is 2^n or it's the last level.
This breaks the problem down into three smaller problems:
- Counting the nodes in a tree.
- Finding the depth of a tree.
- Performing a level order traversal and counting nodes on each level.
deceptikon
Challenge Accepted
3,499 posts since Jan 2012
Reputation Points: 822
Solved Threads: 481
Skill Endorsements: 58
Also note that you might be able to skip transversal if the number of nodes isn't a power of 2. If it is, then you have to transverse just to make sure it fits the definition.
firstPerson
Industrious Poster
4,046 posts since Dec 2008
Reputation Points: 851
Solved Threads: 626
Skill Endorsements: 15