开发者

In Erlang, how to write a BFS Tree Search to find a specific node

开发者 https://www.devze.com 2023-03-01 07:54 出处:网络
I want to write a function to find a specific node in a BFS Tree Search. How to do it in E开发者_运维技巧rlang?Assuming a simple structure:

I want to write a function to find a specific node in a BFS Tree Search.

How to do it in E开发者_运维技巧rlang?


Assuming a simple structure:

node() :: {Key :: term(), Left :: node(), Right :: node()} | undefined.

This function would perform a breadth-first search over the tree and return the depth of the first element found (returns false if no node is found):

find(_Key, undefined) -> false;
find(Key,  Tree)      -> find(Key, [Tree], [], 0).

find(_Key, [], [], _Depth) -> % No more children
    false;
find(Key, [], Children, Depth) -> % Next level, increase depth
    find(Key, Children, [], Depth + 1);
find(Key, [{Key, _, _}|_Rest], _Children, Depth) -> % Found it!
    Depth;
find(Key, [{_, Left, Right}|Rest], Children, Depth) -> % Add children to search
    find(Key, Rest, add(Right, add(Left, Children)), Depth).

add(undefined, List) -> List;
add(E,         List) -> [E|List].

(An empty tree is just undefined).

0

精彩评论

暂无评论...
验证码 换一张
取 消