【问题标题】:Find Ancestors of a given Node in a Binary Tree在二叉树中查找给定节点的祖先
【发布时间】:2021-09-07 04:18:00
【问题描述】:

我试图解决“查找给定节点的祖先”的问题。事实上,我能够解决这个问题。但我有一个附加问题,我无法更改逻辑

假设二叉树如下所示:

     100
    /   \
   45    150
  /  \   /  \
40   60 120 200

节点 60 的共同祖先是 100,45。

我的代码:

def helper(node,k,path):
    
    if node is None:
        return path
            
    path.append(node.data) # Append every node as we visit
    if path[-1]==k: #Once we find the desired Node, print the list till last element
        print(path[:-1])

    path = helper(node.left,k,path)
    
    path = helper(node.right,k,path)
    
    del path[-1] #while backtracking , remove the leaf node
    
    return path
    
def findCommonAns(root,k):
    if root is None:
        return None
    
    if root.data == k:
        return [root.data]
    helper(root,60,[])
    

findCommonAns(tree.root,60)

我的附加问题是,如果我想返回列表(路径)而不是打印,我该如何修改这个逻辑?由于我现在学习递归只有一周,我发现很难修改上述逻辑。

非常感谢任何帮助。谢谢!

【问题讨论】:

  • @ggorlen ,其实我想了解如何修改上面的逻辑,这样我就可以返回列表而不是打印。
  • 部分是的,但是我尝试将路径列表从 findCommonAns 传递给辅助方法并解决了问题。
  • 您的示例树恰好是 BST。总是这样吗?

标签: python algorithm recursion binary-tree


【解决方案1】:
def helper(node,k,path):
    #If node is empty, that is if either root is None,
    #or if we have gone beyon leaf node, result the path list
    if node is None:
        return path
            
    path.append(node.data) #Append data as we visit
    if path[-1]==k:#If last item of the list is the node
        return path[:-1] # return the elemenet till the last element

    path = helper(node.left,k,path)
    
    path = helper(node.right,k,path)
    
    del path[-1]
    
    return path
    

def findCommonAns(root,k):
    if root is None:
        return None
    
    if root.data == k:
        return [root.data]
    path=[]
    helper(root,k,path)
    return path[:-1]

findCommonAns(tree.root,60)

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2019-06-25
    • 2018-10-07
    • 1970-01-01
    • 1970-01-01
    • 2011-09-04
    • 1970-01-01
    • 2020-02-06
    • 1970-01-01
    相关资源
    最近更新 更多