二叉树方法

时间:2013-03-15 02:24:59

标签: python tree binary-tree

我正在尝试编写一个函数,该函数返回叶节点列表的元组和二叉树的内部节点列表。

所以我尝试这样做的方法是初始化两个列表(一个用于叶节点,另一个用于内部节点)。

我已经编写了我的代码,它应该可以正常工作,但只有一个问题。因为我必须递归地执行它,所以我必须自己调用该函数,这意味着列表的初始化将再次发生,这将简单地重置列表。这不是我想要的。我想继续向这些列表添加元素并最终返回它们......

编辑:对不起,我无法添加我的代码,但我可以给你一个粗略的想法:

list1=[]
list2=[]
if (leaf node reached):
            add leaf node to list1

else:
            add node to list2
            call the function on the left child
            call the function on the right child
return (leaves_data,internals_data)

2 个答案:

答案 0 :(得分:0)

在某种程度上,您应确保初始化仅发生一次。有不同的方法可以做到这一点。

这样做的一种方法是在函数外部进行初始化,假设你有这样的东西(伪代码):

function recursiveFunction():
    // Here you had your old init code, you don't need it here anymore
    // Here your function is the same as before
    // [ ... ]
    recursiveFunction()
    return; // Some return statement
end 

// Init stuff here (make sure these variables/list you init are globally defined, so they can be accessed from inside the function
// Then call your recursive function:
recursiveFunction()

另一个简单(但不一定很漂亮)的方法是在init完成后将一些全局变量设置为true,例如:

global variable init_is_done = false // Make sure this can be accessed inside your function

function recursiveFunction():
    // Check if init_is_done is true before doing init
    if not init_is_done:
        // Have your init code here
        init_is_done = true
    endif

    // Here your function is the same as before
    // [ ... ]
    recursiveFunction()
    return; // Some return statement
end 

// Now you can just call your function
recursiveFunction()

根据您使用的语言,不同的方法可能会很好。我当然会尝试在函数外部使用init函数。希望这对你有用。

答案 1 :(得分:0)

在每个递归步骤中,您最初创建一个空列表,仅存储来自该迭代的数据。然后调用递归函数,该函数有望返回包含更多内容的其他列表。您将返回的列表附加到您的,并且您将对递归函数迭代的树的相关分支具有正确的部分结果。最后,从函数返回合并列表,允许树的上层再次附加结果并增加结果,直到它返回到根级别。

这称为递归步骤,只要递归的基数(即使递归停止的规则)正确就行。

def get_nodes(l):
    # Recursion base
    if l is None: return ([], [])
    if l.children is None: return ([], [l])

    # Recursion step
    this = ([l], [])
    internal, leaf = get_nodes(l.children.left)
    this[0] += internal
    this[1] += leaf

    internal, leaf = get_nodes(l.children.right)
    this[0] += internal
    this[1] += leaf

    return this

(注意:未经测试的伪代码,只是一个例子)

以上所有描述都是概念性的,应该被认为是简单的实现。但是在实际实现中,您将避免多次创建和追加多个列表。您可以通过将列表移动到全局范围并使用global关键字将全局值绑定到局部变量来在代码中执行此操作。

相关问题