Hello again.I recently have been doing a assignment which asks us to write a function to check whether a tree is perfectly balanced.I know the concept of Perfectly balanced tree but I just cant make out how to write this function.Any help in right direction will be highly welcome.
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:
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))
return empty or (balanced and height_diff <= 1)
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.
Thank you so much you all for your kind relpies.I have finished making my function.My function does the following:
1)Counts the total number of nodes of the tree.
2)Counts the numbers of nodes on the last level.
3)Determine the depth of the tree.
4)Total nodes-last level nodes.
5)Compare the answer to 2 pow (height-1) -1.
And it worked.
Using your definition of a perfectly balanced tree (I would call it an optimally packed tree), I think the following algorithm would work. If I'm wrong please let me know.
Traverse each path measuring its length.
Keep track of the longest and shortest paths measured.
If, at any time during the scan, the difference between longest and shortest
is greater than 1, the tree is not balanced.
If the tree is perfectly balanced you'll have to traverse the whole tree but if it's unbalanced you won't.