简体   繁体   English

递归 function 不返回 python 中的数组

[英]Recursive function does not return array in python

I'm writing a simple code that returns the path to the destination node in BST.我正在编写一个简单的代码,它返回 BST 中目标节点的路径。

在此处输入图像描述

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

root = TreeNode(6)
root.left = TreeNode(2)
root.right = TreeNode(8)
root.left.left = TreeNode(0)
root.left.right = TreeNode(4)
root.left.right.left = TreeNode(3)
root.left.right.right = TreeNode(5)
root.right.left = TreeNode(7)
root.right.right = TreeNode(9)

After defining the tree;定义树之后;

p = 2
q = 8

def pathFind(path, cur, node): # path : path the function walked throug so far
                               # cur : current node
                               # node : destination node's value 
  
  #print(f'current node value is {cur.val}')
  #print(path)
  ## ending condition ##
  if cur.val == node: # If we reach the destination node
    return path
  
  elif cur.val < node and cur.right != None : 
    # 'if cur.right != None:' line is useless since the problem guarantees the existence of destination value in BST 
    path.append(cur)

    return pathFind(path, cur.right, node)
  elif cur.val > node and cur.left != None: # cur.val > node:
    path.append(cur)
    return pathFind(path, cur.left, node)
  else:
    return None

path_p = pathFind([root], root, p) 

I checked that my function reaches the destination and record the path toward it without any problem, but the last line - path_p = pathFind([root], root, p) doesn't work.我检查了我的 function 是否到达目的地并记录通往目的地的路径没有任何问题,但最后一行 - path_p = pathFind([root], root, p) 不起作用。

Anyone could help?任何人都可以帮忙吗?

In function pathFind() , the path is returned only by the execution where the tested node contains the target value.在 function pathFind()中,路径仅由测试节点包含目标值的执行返回。 The (all) previous executions discard that return value. (所有)先前的执行丢弃该返回值。 Fix it by putting return before the recursive calls.通过在递归调用之前放置return来修复它。

Try below code to find the path for a target node尝试以下代码以查找目标节点的路径

def pathFind(path, node, target):
    if node == None:
        return
    else:
        path.append(node.val)
        if node.val == target:
            return path
        elif node.val < target and node.right != None:
            return pathFind(path, node.right, target)
        elif node.val > target and node.left != None:
            return pathFind(path, node.left, target)
        else:
            return None

print(pathFind([], root, 9))

output output

[6, 8, 9]

A few remaining issues (after the edits to your question):剩下的几个问题(在编辑您的问题之后):

  • The root node is in most cases added twice to the path: once in the initial call, and again when moving to the left or right subtree of the root node: cur is the root node and path.append(cur) is executed.在大多数情况下,根节点会被两次添加到路径中:一次是在初始调用中,另一次是在移动到根节点的左子树或右子树时: cur是根节点并执行path.append(cur)

    So, pass an empty list in the initial call instead of [root]因此,在初始调用中传递一个空列表而不是[root]

  • When the target node is found, that node is not appended to the path, yet I suppose it should be the final node in the path.找到目标节点后,该节点不会附加到路径中,但我想它应该是路径中的最后一个节点。 So path.append(cur) should also happen in the first if block.所以path.append(cur)也应该发生在第一个if块中。

Those changes will fix your code.这些更改将修复您的代码。

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

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