【问题标题】:Printing a path to the tree's node as a list将树节点的路径打印为列表
【发布时间】:2020-05-28 01:33:14
【问题描述】:

我有点发疯了。

我的目标很简单。在二叉树中,给出一个节点并以列表的形式返回该节点的路径。 有许多可用的实现。

Here 是最好和最直接的之一:

def path(root, k):
    if not root:
        return []
    if root.val == k:
        return [root.val]
    res = path(root.left, k)
    if res:
        return [root.val] + res
    res = path(root.right, k)
    if res:
        return [root.val] + res
    return []

出于纯粹的教育原因,我决定用一个辅助函数重写它,在该函数中我传递一个空列表并递归地向其中添加元素。

class TreeNode:
    def __init__(self, x):
        self.val = x
        self.left = None
        self.right = None

    def path2Node2(self, root, node2):
        if not root:
            return None

        def _helper(root, node, paths):
            if not root:
                return []
            if root.val == node.val:
                paths.append(root.val)
                return paths
            return _helper(root.left, node, paths + [root.val])
            return _helper(root.right, node, paths + [root.val])


        return _helper(root, node2, [])


if __name__ == '__main__':
    l = TreeNode(10)
    l.left = TreeNode(8)
    l.right = TreeNode(2)
    l.left.left = TreeNode(3)
    l.left.right = TreeNode(5)
    l.right.left = TreeNode(4)
    print(l.path2Node2(l, l.left))

如果我通过根节点(print(l.path2Node2(l, l)),它就可以工作。

如果我通过左孩子(print(l.path2Node2(l,l.left))

但如果我通过 l.left.right 或 l.right.left,它会返回 []。

在过去的几个小时里我无法弄清楚。我错过了什么?

【问题讨论】:

    标签: python list tree binary-tree


    【解决方案1】:

    看来您正在解决今天的 CodeSignal 挑战。这是我的 Python3 解决方案。希望对您有所帮助。

    #
    # Binary trees are already defined with this interface:
    # class Tree(object):
    #   def __init__(self, x):
    #     self.value = x
    #     self.left = None
    #     self.right = None
    def findCommonValues(t1, t2):
        def dfs(node:Tree, vals:list, comparison:dict=None):
            """Run a depth-first search on the tree by passing the root. If comparison is passed, then it
            is used to determine if we should add the value of node to the vals list. Otherwise, always
            add value to the vals list."""
            if not node:
                return
            if node.left:
                dfs(node.left, vals, comparison)
            if comparison is None or node.value in comparison:
                vals.append(node.value)
            if node.right:
                dfs(node.right, vals, comparison)
    
        # Create an empty list and use it to gather all the values from the first Tree
        vals = []
        dfs(t1, vals)
        # This line coverts my list to a dict, where each item in the list is a key, and the val is 
        # arbitrary (it will just be an incremented int here). This way, we can search for previous values
        # with constant run time.
        comparison = {k: v for v, k in enumerate(vals)}
        # Reset the list and process the 2nd Tree
        vals = []
        dfs(t2, vals, comparison)
        # Now the vals list has what we're looking for, thanks to line 17 in dfs
        return vals
    

    对于那些在未来看到这个的人,here 是 CodeSignal(以前的 CodeFights)挑战的链接。

    【讨论】:

    • 谢谢!我没有使用 CodeSignal(主要是 CodeWars 和 LeetCode)。我重写了我的,但它仍然没有帮助: if root.left: return _helper(root.left, node, paths + [root.val]) if root.right: return _helper(root.right, node, paths + [ root.val])
    【解决方案2】:

    所以,这是我自己问题的答案。

    class TreeNode:
        def __init__(self, x):
            self.val = x
            self.left = None
            self.right = None
    
        def path2Node2(self, root, node2):
            if not root:
                return []
    
            def _helper(root, node, paths):
                if not root:
                    return []
                if root.val == node.val:
                    paths.append(root.val)
                    return paths
                l = _helper(root.left, node, paths + [root.val])
                r =  _helper(root.right, node, paths + [root.val])
                if l: return l
                if r: return r
    
            return _helper(root, node2, [])
    
    
    if __name__ == '__main__':
        l = TreeNode(10)
        l.left = TreeNode(8)
        l.right = TreeNode(2)
        l.left.left = TreeNode(3)
        l.left.right = TreeNode(5)
        l.right.left = TreeNode(4)
        print(l.path2Node2(l, l.right))
    

    我添加了两行:

    if l: return l
    if r: return r
    

    但还是不明白我原来的方法有什么不同。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2016-08-16
      • 1970-01-01
      • 1970-01-01
      • 2021-09-19
      相关资源
      最近更新 更多