Finding Depth of Perfect & Complete Binary Trees

Join the discussion
Ask a follow-up here, or get your own question answered by working scientists, mathematicians and engineers — people, not an autocomplete.
Real named experts · corrections over time · the nuance an AI answer skips
1 replies · 2K views
evinda
Gold Member
MHB
Messages
3,741
Reaction score
0
Hi! (Wave)

How can we find the depth of a perfect binary tree and how of a complete one? (Thinking)

Since a perfect binary tree is a full binary tree, at which the leaves have the same depth, I thought that we can find the depth, by just looking at the leftmost nodes, like that:

Code:
Algorithm(NODE *tree){
pointer p=tree;
int depth=0;
while (p!=NULL){
         p=p->next;
         depth++;
} 
return depth;
}
A complete binary tree of height $h$ consists of a perfect binary tree of height $h-1$, at which, one or more leaves with height $h$, have been added.
The leaves have been placed at the leftmost positions of the tree.

I thought that we could use again the above algorithm.

Am I right or have I done someething wrong? (Thinking)
 
on Phys.org
evinda said:
Hi! (Wave)

How can we find the depth of a perfect binary tree and how of a complete one? (Thinking)

Since a perfect binary tree is a full binary tree, at which the leaves have the same depth, I thought that we can find the depth, by just looking at the leftmost nodes, like that:

Code:
Algorithm(NODE *tree){
pointer p=tree;
int depth=0;
while (p!=NULL){
         p=p->next;
         depth++;
} 
return depth;
}
A complete binary tree of height $h$ consists of a perfect binary tree of height $h-1$, at which, one or more leaves with height $h$, have been added.
The leaves have been placed at the leftmost positions of the tree.

I thought that we could use again the above algorithm.

Am I right or have I done someething wrong? (Thinking)

If the tree truly does have all its leaves at the same depth, this algorithm should work fine.

On the other hand, if you're not guaranteed a tree where all leaves are at the same depth, I don't see any way of computing the depth of the tree other than a full traversal.

[EDIT] You did mean
Code:
p = p->lc
, right?