BST subtree


  • 0

    Implement a subtree function to cut the BST by the given range, inclusive, and then return the root of this subtree.

    TreeNode subtree(TreeNode root, int min, int max )
    

  • 0

    @yubad2000 Could you specify company tag? Thank you


  • 0

    @elmirap How to do that?


  • 0

    @yubad2000 I am not sure about this. But I can propose you to write the company tag in the problem description. I suppose that later admins will move the problem in the appropriate discussion group.


  • 0

    @yubad2000 What will be the output of this example?Range is [37..55]. Do we need to trim all substrees out of range? Thank you

    ---------------50------
    ---------30---------80
    -----------------54------
    ----------------------72

  • 0

    @elmirap said in BST subtree:

    What will be the output of this example?Range is [37..55]. Thank you
    ---------------50------
    ---------30---------80
    -----------------54------
    ----------------------72

    The result should be also a BST, so could be:

                50
                   \
                   54
    

    or

                54
              /
           50
    

  • 0

    @yubad2000

    def trimTree(root, min, max):
        if root != None:
            if root.val >= min and root.val <= max:
                root.left = trimTree(root.left, min, max)
                root.right = trimTree(root.right, min, max)            
            elif root.val > max:
                return trimTree(root.left, min, max)
            else:
                return trimTree(root.right, min, max)
        return root

Log in to reply
 

Looks like your connection to LeetCode Discuss was lost, please wait while we try to reconnect.