开发者

Leetcode question 700, search in a tree problem. my code keeps returning an empty array

even though I have appended item into my array while recursively going through the tree, my code returns an empty array every time I try to run it.

the question is asking 开发者_Python百科me: You are given the root of a binary search tree (BST) and an integer val.

Find the node in the BST that the node's value equals Val and return the subtree rooted with that node. If such a node does not exist, return null.

# Definition for a binary tree node.
# class TreeNode:
#     def __init__(self, val=0, left=None, right=None):
#         self.val = val
#         self.left = left
#         self.right = right
class Solution:
    def searchBST(self, root: Optional[TreeNode], val: int) -> Optional[TreeNode]:
        array=[]
        if root is None:
            return
        if root.val==val:
            newroot=root
            def BSThelper(newroot,val,array):
                array.append(newroot.val)-- ------------as you can see ive appended the values in here but
                BSThelper(newroot.left,val,array)
                BSThelper(newroot.right,val,array)
                return array 
        self.searchBST(root.left,val)
        self.searchBST(root.right,val)
        

what I need to code to do is the return the subtree of the given value and ive seen other solution's but I'm very confused what is wrong with this code because in my head this seems to make sense.

please excuse me if this method turns out to be completely wrong I'm quite new the python and only started a few months ago( start of the academic year for uni).


It sounds like you're trying to find a node in a binary search tree and return the subtree rooted at that node. There could be a few reasons why your code is not working as expected. Here are some suggestions for troubleshooting the issue:

Check if the val you're searching for is actually in the tree. You can do this by traversing the tree and checking if any of the nodes have the value you're looking for. If the value is not in the tree, your code will always return an empty array.

Make sure you're correctly adding nodes to your array as you traverse the tree. When traversing a tree, it's common to use a recursive function that processes the current node, then recursively calls itself on the left and right subtrees. Within this recursive function, you should be adding the nodes to your array as you encounter them.

Check if your array is being reset or overwritten at any point in your code. If the array is being reset or overwritten, you will end up with an empty array even if you've added items to it while traversing the tree.

I hope these suggestions help you troubleshoot the issue with your code. If you continue to have problems, please provide more information about your code and the steps you've taken to try to fix it.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜