Erlang二叉树函数 [英] Erlang Binary Tree function

查看:174
本文介绍了Erlang二叉树函数的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一棵完美的二叉树,每个节点都这样表示

I have a Perfect Binary Tree which every node is represented like that

[Value, LeftNode, RightNode] 

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, [], []]

示例:

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). 

在我们的示例中,它返回4:L1的值. 返回没有最后一个左叶的树的函数:它将该叶替换为[]

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].

在我们的示例中,它返回的树不包含L1:被[]替换为

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.

推荐答案

您可以组合编写的两个函数,并使新函数返回格式为{Value, NewTree}的结果.对于您已经处于困境的情况,这很简单:

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]}.

这篇关于Erlang二叉树函数的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆