Similarly:
height(t) = if (t==NULL) then 0 else 1+max(height(t.left),height(t.right))
You have:
perfect(t) = if (t==NULL) then 0 else { let h=perfect(t.left) if (h != -1 && h==perfect(t.right)) then 1+h else -1 }
Where perfect (t) returns -1 if the leaves are not all at the same depth, or if any node has only one child; otherwise, it returns the height.
Edit: this is for "complete" = "An ideal binary tree is a complete binary tree in which all leaves are at the same depth or level. 1 (This is also ambiguously called a complete binary tree.)" ( Wikipedia ).
Here's a recursive check for: "A complete binary tree is a binary tree in which each level, with the possible exception of the last, is completely populated and all nodes as far as possible.". It returns (-1, false) if the tree is not completed, otherwise (height, full), if there is one, with the full value true, if it is perfect.
complete(t) = if (t==NULL) then (0,true) else { let (hl,fl)=complete(t.left) let (hr,fr)=complete(t.right) if (fl && hl==hr) then (1+h,fr) else if (fr && hl==hr+1) then (1+h,false) else (-1,false) }
Jonathan graehl
source share