prolog:在二叉搜索树中搜索

时间:2013-12-30 22:13:58

标签: prolog

我需要将列表转换为二进制搜索树,然后搜索此树中的年龄范围并返回包含这些值的列表,并返回检查数以构建输出列表。

我花了两天时间尝试这样做,但它总是返回假

这是我在mbratch的帮助下达到的最后一个代码:

 my_list( [[30,'john'], [58,'alex'], [14,'randy'], [65,'shawn'], [67,'jack']] ).

 construct(L,T) :- construct(L,T,nil).

 construct([],T,T).
 construct([N|Ns],T,T0) :- add(N,T0,T1), construct(Ns,T,T1).

 add(X, nil, node(X, nil, nil)).
 add(X, node(Root, L, R),node(Root, L1, R)) :- X @< Root, add(X, L, L1).
 add(X, node(Root, L, R),node(Root, L, R1)) :- X @> Root, add(X, R, R1).

 findInRange(R1, R2, T, S, N) :- find(R1, R2, T, S, N),!.

 find(_R1,_R2, nil, [], 0).
 find(R1, R2, node([Age,Name],L,R), S, N) :-
    R1 =< Age,R2 >= Age, % is the age OK (in range), if it is check left and 
    find(R1, R2, L, LL, NL),
    find(R1,R2,R,LR,NR),
    append([[Age,Name]],LL,X),
    append(X,LR,S),
    N is NL+NR+1.
 find(R1, R2, node([Age,Name],L,R), [], 0) :-
    Age > R2;Age<R1.               % if the age is greater than R2, return []
 find(R1, R2, node([Age,Name],L,R), LL, N) :-
    R1 < Age, % if the age is bigger than R1 search the left tree return LL
    find(R1,R2,L,LL,NL),
    N is NL+1.
 find(R1, R2, node([Age,Name],L,R), LR, N) :-
    R2 > Age, % if the age smaller than R1 search the right tree return LR
    find(R1,R2,R,LR,NR),
    N is NR+1.

这是我的疑问:

     my_list(Z), construct(Z, T), findInRange(11, 15, T, S, N).

它应该重新调整[[14,'randy']]和支票数量。

为什么它返回空列表并且N = 0?

1 个答案:

答案 0 :(得分:0)

我认为这样做会有所帮助。我运行了您发布的查询并获得了S = [[30, john], [14, randy]]

my_list( [[30,'john'], [58,'alex'], [14,'randy'], [65,'shawn'], [67,'jack']] ).

construct(L,T) :- construct(L,T,nil).
construct([],T,T).
construct([N|Ns],T,T0) :- add(N,T0,T1),construct(Ns,T,T1).

add(X, nil, node(X, nil, nil)).
add(X, node(Root, L, R),node(Root, L1, R)) :- X @< Root, add(X, L, L1).
add(X, node(Root, L, R),node(Root, L, R1)) :- X @> Root, add(X, R, R1).

findInRange(R1, R2, T, S, N) :- find(R1, R2, T, S, N),!.

find(_R1,_R2, nil, [], 0).
find(R1, R2, node([Age,Name],L,R), S, N) :-
            R1 =< Age,R2 >= Age, % is the age OK (in range), if it is check left and right side
            find(R1, R2, L, LL, NL),
            find(R1,R2,R,LR,NR),
            append([[Age,Name]| LL],LR,S),
            N is NL+NR+1.

find(R1, R2, node([Age,Name],L,R), LL, N) :-
            Age > R2, % if the age is bigger than R2 search the left tree return LL
            find(R1,R2,L,LL,NL),
            N is NL+1.
find(R1, R2, node([Age,Name],L,R), LR, N) :-
            R1 > Age, % if the age smaller than R1 search the right tree return LR
            find(R1,R2,R,LR,NR),
            N is NR+1.