I am just wondering if someone might be able to clarify the definition of a balanced tree for me. I have that \"a tree is balanced if each sub-tree is balanced and the heigh
There are several ways to define "Balanced". The main goal is to keep the depths of all nodes to be O(log(n)).
It appears to me that the balance condition you were talking about is for AVL tree.
Here is the formal definition of AVL tree's balance condition:
For any node in AVL, the height of its left subtree differs by at most 1 from the height of its right subtree.
Next question, what is "height"?
The "height" of a node in a binary tree is the length of the longest path from that node to a leaf.
There is one weird but common case:
People define the height of an empty tree to be
(-1).
For example, root's left child is null:
A (Height = 2)
/ \
(height =-1) B (Height = 1) <-- Unbalanced because 1-(-1)=2 >1
\
C (Height = 0)
Two more examples to determine:
Yes, A Balanced Tree Example:
A (h=3)
/ \
B(h=1) C (h=2)
/ / \
D (h=0) E(h=0) F (h=1)
/
G (h=0)
No, Not A Balanced Tree Example:
A (h=3)
/ \
B(h=0) C (h=2) <-- Unbalanced: 2-0 =2 > 1
/ \
E(h=1) F (h=0)
/ \
H (h=0) G (h=0)