我实现了这个树(插入),但我想跟踪重复,我该怎么做。
insert2(nil, nil, nil).
insert2(Info, nil, t((Info,1), nil, nil)).
insert2(Info , t((RootInfo,_), Left, Right),
t((RootInfo,_), LeftPlus, Right)) :-
Info< RootInfo,
insert2(Info, Left, LeftPlus).
insert2(Info , t((RootInfo,count), Left, Right),t((RootInfo,count+1), Left, Right)) :-
Info= RootInfo.
insert2(Info, t((RootInfo,_), Left, Right),
t((RootInfo,_), Left, RightPlus)) :-
RootInfo< Info,
insert2(Info, Right, RightPlus).
更明确一点,这就是我的意思
-? T = t((20,3),t((10,1),nil,nil),t((30,2),nil,nil)),
insertT(10,T,NT).
NT = t((20,3), t((10,2),nil,nil),t((30,2),nil,nil)).
由于我已插入10,因此树只会增加计数器而不是添加重复值。感谢
答案 0 :(得分:1)
由于你非常接近,我会把它整理好。 :)
你所拥有的唯一真正的问题是:
Count
有一个原子而不是变量
Count + 1
作为参数,它将被视为术语+(Count, 1)
,除非它被传递到可以对其进行评估的谓词(如is/2
或算术比较) insert2(nil, nil, nil)
。或者至少如果您打算考虑插入nil
,我认为结果应该是原始树,所以它应该是insert2(nil, Tree, Tree)
。您不会因为尝试插入nil
而使树无效。你会单独留下树。考虑这些因素:
% (3) Inserting nil into a Tree yields the same Tree
insert(nil, Tree, Tree).
% If you insert into an empty tree, the result is a tree with
% a single node consisting of your new info
insert(Info, nil, t((Info, 1), nil, nil)).
% (1) If you insert into a tree and the node at the top matches your
% Info, then you only increment the count of the top node
insert(Info, t((Info, C), L, R), t((Info, Cx), L, R)) :-
Cx is C + 1. % (2) `is/2` will evaluate; you can't do this "in-line"
% If you insert Info which is smaller than the top node value of
% a non-nil tree, then you insert the Info into the left branch
insert(Info, t((I, C), L, R), t((I, C), Lx, R)) :-
Info < I,
insert(Info, L, Lx).
% If you insert Info which is greater than the top node value of
% a non-nil tree, then you insert the Info into the right branch
insert(Info, t((I, C), L, R), t((I, C), L, Rx)) :-
Info > I,
insert(Info, R, Rx).