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
).
精彩评论