欢迎您访问程序员文章站本站旨在为大家提供分享程序员计算机编程知识!
您现在的位置是: 首页

Python 实现二叉树并搜索节点值和为某一值的路径

程序员文章站 2022-07-09 12:39:58
...

python实现:

import copy
class Node: 
    def __init__(self,value):
        self.value  = value
        self.Lchild = None
        self.Rchild = None
    def addLchild(self,node):
        self.Lchild=node
    def addRchild(self,node):
        self.Rchild=node

def Findpath(root,currentsum):
    global truepath
    currentsum = currentsum+ root.value
    nodepath.append(root.value)
    if currentsum == sumx:
        truepath.append(copy.deepcopy(nodepath))
    if currentsum < sumx:
        if root.Lchild is not None:
            Findpath(root.Lchild,currentsum)
        if root.Rchild is not None:
            Findpath(root.Rchild,currentsum)
    nodepath.pop()

nodepath = []
truepath = []

if __name__ == "__main__":
    root = Node(1)
    node1 = Node(2)
    node2 = Node(3)
    root.addLchild(node1)
    root.addRchild(node2)
    sumx = 3
    currentsum=0

    Findpath(root,currentsum)
    print(truepath)

需要注意的是在truepath.append(copy.deepcopy(nodepath))这部分必须使用深拷贝才能保存当时的值