Write The Shortest Program To Check If A Binary Tree Is Balanced
Jelly, 11 bytes
ḊµŒḊ€IỊ;߀Ạ
Try it online!
The empty tree is represented by []
.
Prolog (SWI), 49 bytes
N+_/B/C:-X+B,Y+C,abs(X-Y)<2,N is max(X,Y)+1.
0+e.
Try it online!
Represents trees as Value/Left_Child/Right_Child
, with the empty tree being the atom e
. Defines +/2
, which outputs through success or failure, with an unbound variable (or one already equal to the tree's height) on the left and the tree on the right--if the height argument is unacceptable, add 9 bytes to define -T:-_+T.
.
N + _/B/C :- % If the second argument is a tree of the form _Value/B/C,
X+B, % X is the height of its left child which is balanced,
Y+C, % Y is the height of its right child which is balanced,
abs(X-Y) < 2, % the absolute difference between X and Y is strictly less than 2,
N is max(X,Y)+1. % and N is the height of the full tree.
0 + e. % If, on the other hand, the second argument is e, the first is 0.
JavaScript (Node.js), 49 bytes
h=([l,r])=>l?(d=h(l)-h(r))*d<2?1+h(d>0?l:r):NaN:1
Try it online!
-9 bytes by Arnauld.
JavaScript, 58 bytes
h=([l,r])=>l?(l=h(l),r=h(r),m=l>r?l:r,m+m-l-r<2?m+1:NaN):1
Try it online!
Use []
for null, and [left, right, value]
for nodes.