Prolog, reconstruct BST trees from inorder list

后端 未结 2 356
误落风尘
误落风尘 2021-01-18 16:28

We well know inorder implementation for BST tree.

inorder(nil, []).
inorder(t(Root, L, R), List) :-
    inorder(L, ListLeft),
    inorder(R, Lis         


        
2条回答
  •  礼貌的吻别
    2021-01-18 17:01

    If you like the trick I've proposed here, the only change required could be

    :- use_module(carlo(snippets/when_)).
    
    inorder(t(Root, L, R), List) -:- ...
    

    and now

    ?- inorder(T,[1,2,3]).
    T = t(1, nil, t(2, nil, t(3, nil, nil))) ;
    T = t(1, nil, t(3, t(2, nil, nil), nil)) ;
    T = t(2, t(1, nil, nil), t(3, nil, nil)) ;
    T = t(3, t(1, nil, t(2, nil, nil)), nil) ;
    T = t(3, t(2, t(1, nil, nil), nil), nil) ;
    false.
    

提交回复
热议问题