问题
I have a Perfect Binary Tree which every node is represented like that
[Value, LeftNode, RightNode]
Value is the node value and each LeftNode and RightNode are the Node's sons which are too Binary Trees recursively. And the last nodes (leafs) are represented like that
[Value, [], []]
example:
L1=[4, [], []],
L2=[5, [], []],
L3=[6, [], []],
L4=[7, [], []],
L5=[2, L1, L2],
L6=[3, L3, L4],
Tree=[1,L5 , L6].
so I have the function that returns the last left leaf
lastLeftLeaf([H, [], []]) ->H;
lastLeftLeaf([H, Left, Right]) ->lastLeftLeaf(Left).
in our example it returns 4 :the value of L1. And the function that returns the tree without last left leaf:it replaces this leaf with []
withoutLastLeftLeaf([H, [], []]) ->[] ;
withoutLastLeftLeaf([H, Left, Right]) ->[H, withoutLastLeftLeaf(Left), Right].
in our example it returns the tree without L1: which replaced with []
both the functions do the same browse and to get results i must do two browses and for more performance and efficiency i want to create a function with just one browse that returns two results : the last left leaf and the tree without that leaf any help and thank you all.
回答1:
You can combine the two functions you have written, and have the new function return a result of the form {Value, NewTree}
. For the case where you're already at the leaf, it's simple:
take_last_left_leaf([H, [], []]) -> {H, []};
Then, at any other point in the tree, you would recurse into the left branch, get the value and the new left branch, and then return the value along with the modified tree:
take_last_left_leaf([H, Left, Right]) ->
{Value, NewLeft} = take_last_left_leaf(Left),
{Value, [H, NewLeft, Right]}.
来源:https://stackoverflow.com/questions/61477730/erlang-binary-tree-function