-module(ltree).
-export([is_leaf/1,sum/1,max/1,is_ordered/1,insert/2]).
-export([test/0]).
-record(btree, {value, ltree=nil, rtree=nil}).
% 判断某个节点是否为叶子节点
is_leaf(#btree{ltree=nil,rtree=nil}) ->
true;
is_leaf(#btree{}) ->
false.
% 整棵树所有节点的值的和
sum(#btree{value=Value, ltree=nil, rtree=nil}) ->
Value;
sum(#btree{value=Value, ltree=nil, rtree=Rtree}) ->
sum(Rtree) + Value;
sum(#btree{value=Value, ltree=Ltree, rtree=nil}) ->
sum(Ltree) + Value;
sum(#btree{value=Value, ltree=Ltree, rtree=Rtree}) ->
sum(Ltree) + sum(Rtree) + Value.
% 整棵树节点值的最大值
max(#btree{value=Value, ltree=nil, rtree=nil}) ->
Value;
max(#btree{value=Value, ltree=nil, rtree=Rtree}) ->
erlang:max(Value, max(Rtree));
max(#btree{value=Value, ltree=Ltree, rtree=nil}) ->
erlang:max(Value, max(Ltree));
max(#btree{value=Value, ltree=Ltree, rtree=Rtree}) ->
erlang:max(Value, erlang:max(max(Ltree), max(Rtree))).
% 判断一个二叉树是否有序的
is_ordered(#btree{ltree=nil, rtree=nil}) ->
true;
is_ordered(#btree{value=Value, ltree=Ltree, rtree=nil}) ->
if
Value >= Ltree#btree.value ->
is_ordered(Ltree);
true -> false
end;
is_ordered(#btree{value=Value, ltree=nil, rtree=Rtree}) ->
if
Value =< Rtree#btree.value ->
is_ordered(Rtree);
true -> false
end;
is_ordered(#btree{value=Value, ltree=Ltree, rtree=Rtree}) ->
if
Value >= Ltree#btree.value, Value =< Rtree#btree.value ->
is_ordered(Ltree),
is_ordered(Rtree);
true -> false
end.
% 如果一个二叉树是有序的,往该树再插节点,保持树有序
insert(NewValue, #btree{value=Value, ltree=nil, rtree=nil}) ->
if
Value > NewValue ->
#btree{value=Value,
ltree=#btree{value=NewValue},
rtree=nil};
true ->
#btree{value=Value,
ltree=nil,
rtree=#btree{value=NewValue}}
end;
insert(NewValue, #btree{value=Value, ltree=Ltree, rtree=nil}) ->
if
Value =< NewValue ->
#btree{value=Value,
ltree=Ltree,
rtree=#btree{value=NewValue}};
true ->
#btree{value=Value,
ltree=insert(NewValue, Ltree),
rtree=nil}
end;
insert(NewValue, #btree{value=Value, ltree=nil, rtree=Rtree}) ->
if
Value > NewValue ->
#btree{value=Value,
ltree=#btree{value=NewValue},
rtree=Rtree};
true ->
#btree{value=Value,
ltree=nil,
rtree=insert(NewValue, Rtree)}
end;
insert(NewValue, #btree{value=Value, ltree=Ltree, rtree=Rtree}) ->
if
Value > NewValue ->
#btree{value=Value,
ltree=insert(NewValue, Ltree),
rtree=Rtree};
true ->
#btree{value=Value,
ltree=Ltree,
rtree=insert(NewValue, Rtree)}
end.
test()->
Btree1 = #btree{value=1},
Btree2 = #btree{value=4,
ltree=#btree{value=3},
rtree=#btree{value=5}},
Btree3 = #btree{value=3, % Btree3是有序的
ltree=#btree{value=2},
rtree=Btree2},
Btree4 = #btree{value=1,
ltree=#btree{value=2},
rtree=#btree{value=3}},
Btree5 = insert(1, Btree3), % Btree5也是有序的
Btrees = [Btree1, Btree2, Btree3, Btree4, Btree5],
TestPrint =
fun(#btree{}=Btree) ->
io:format("~p~n Sum: ~.3p Max: ~.3p, IsLeaf?: ~.3p, IsOrdered?: ~.3p~n",
[Btree, sum(Btree), max(Btree), is_leaf(Btree), is_ordered(Btree)])
end,
lists:foreach(TestPrint, Btrees).
祝你好运!!!