简体   繁体   English

查找二叉树中的所有路径

[英]Find all paths in a binary tree

I am trying to solve the coding question of "Given a binary tree, return all root-to-leaf paths."我正在尝试解决“给定二叉树,返回所有根到叶路径”的编码问题。

Input:

   1
 /   \
2     3
 \
  5

Output: ["1->2->5", "1->3"]

I have seen one solution我见过一种解决方案

class Solution:
    def binaryTreePaths(self, root: TreeNode) -> List[str]:
        allPath = []
        if root is None:
            return []
        self.find_all_paths_recursive(root, [], allPath)
        return allPath

    def find_all_paths_recursive(self, currNode, currPath, allPath):
        if currNode is None:
            return 
        currPath.append(currNode.val)
        if currNode.left is None and currNode.right is None:
            currOut = '->'.join([str(x) for x in list(currPath)])
            allPath.append(currOut)
        # traverse left sub tree
        self.find_all_paths_recursive(currNode.left, currPath, allPath)
        # traverse right sub tree
        self.find_all_paths_recursive(currNode.right, currPath, allPath)
        del currPath[-1]

Running the above code gave me the answer of ["1->2->5", "1->3"], whcih is correct.运行上面的代码给了我 ["1->2->5", "1->3"] 的答案,这是正确的。

I was thinking by changing the code block under if currNode.left is None and currNode.right is None: to我想通过更改if currNode.left is None and currNode.right is None:下的代码块if currNode.left is None and currNode.right is None:

      if currNode.left is None and currNode.right is None:
            #currOut = '->'.join([str(x) for x in list(currPath)])
            #allPath.append(currOut)
            allPath.append(currPath)

should gave me the results [[1,2,5], [1,3]].应该给我结果 [[1,2,5], [1,3]]。 However, this change returned me the results [[],[]].但是,此更改返回了结果 [[],[]]。 I wonder why this doesn't work?我想知道为什么这不起作用?

Since you want to adding the currPath directly, you have to add a copy of the currPath at that instant.由于您想直接添加 currPath,因此您必须在该时刻添加 currPath 的副本。

Like this:像这样:

if currNode.left is None and currNode.right is None:
    #currOut = '->'.join([str(x) for x in list(currPath)])
    # allPath.append(currOut)
    allPath.append(list(currPath))

EDIT:编辑:

Without adding list you are adding the original list object to allPath which will be updated due to recursion.如果不添加list您就是将原始列表对象添加到 allPath 中,该对象将因递归而更新。 Adding the list will make a copy of the original list object which will be saved and not further updated.添加list将制作copy of the original list objectcopy of the original list object将被保存且不会进一步更新。

Recursion is a functional heritage and so using it with functional style yields the best results.递归是一种函数式遗产,因此以函数式风格使用它会产生最好的结果。 This means avoiding things variable reassignment, other mutations, and side effects.这意味着避免变量重新分配、其他突变和副作用。

Let's see what it would look like to implement btree in this way.让我们看看以这种方式实现btree会是什么样子。 Notice the node properties left and right can be set when a new node is constructed -请注意,可以在构造新节点时设置node属性leftright -

# btree.py

def empty():
  return None

class node:
  def __init__(self, val, left = empty(), right = empty()):
    self.val = val
    self.left = left
    self.right = right

def paths(t, p = ()):
  if not t:
    return
  elif t.left or t.right:
    yield from paths(t.left, (*p, t.val))
    yield from paths(t.right, (*p, t.val))
  else:
    yield "->".join(map(str, (*p, t.val)))

Here's your main program now -现在这是你的main -

# main.py

from btree import node, empty, paths

#    1
#  /   \
# 2     3
#  \
#   5

t = node(1, node(2, empty(), node(5)), node(3))

print(list(paths(t)))
['1->2->5', '1->3']

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM