打印二叉树的所有路径(DFS)

时间:2017-09-23 00:46:21

标签: python binary-tree binary-search

我试图打印二叉树的所有路径(根到叶路径),但无济于事。

我的策略是使用递归,基本情况为either tree is None or tree node is leaf return否则,遍历树的左右两侧。

但我无法找到保留左右树的方法。

def pathSum(self, root, target, result):

    if not root:
        return []

    if not root.left and not root.right:
        return [root.val]

    for i in [root.left, root.right]:
        path = [root.val] + self.pathSum(i, target, result)
        print("path", path)
        return path

2 个答案:

答案 0 :(得分:1)

想法是在每个节点访问时构建路径(列表),如果当前节点是叶子,将当前节点添加到路径并打印它,如果不是,只需添加当前以扩展路径:

def pathSum(self, path):

    if not self.left and not self.right:
        print(path + [self.val])
        return

    self.left.pathSum(path + [self.val])
    self.right.pathSum(path + [self.val])


root.pathSum([])

更新:如果您想保留所有路径:

def pathSum(self, current_path, all_paths):

    if not self.left and not self.right:
        print('Path found: ' + str(current_path + [self.val]))
        all_paths.append(current_path + [self.val])
        return

    self.left.pathSum(current_path + [self.val], all_paths)
    self.right.pathSum(current_path + [self.val], all_paths)

all_paths = []

root.pathSum([], all_paths)

print('All paths: ' + str(all_paths))

答案 1 :(得分:-1)

通过一些迭代,我发现以下解决方案有效。但是,我不确定是否有更有效的方法来查找所有叶根路径。

此解决方案背后的想法是预订遍历

def allPaths(self, root, path, all_path):
    if not root.left and not root.right:
        path.append(root.val)
        all_path.append(path[:])
        return

    if root:
        path.append(root.val)
        self.allPaths(root.left, path, all_path)
        path.pop(-1)
        self.allPaths(root.right, path, all_path)
        path.pop(-1)
    return all_path