Skip to content
The Chat Archive
claude-instant-1· Anthropic Arena Human Preference 55K

Write a function to merge two bsts in python and translate it to Fortran

  1. User

    Write a function to merge two bsts in python and translate it to Fortran

  2. Assistant

    Here is a Python function to merge two BSTs:

    def mergeBSTs(bst1, bst2):
        if not bst1:
            return bst2
        if not bst2:
            return bst1
        
        if bst1.value < bst2.value:
            bst1.right = mergeBSTs(bst1.right, bst2)
            return bst1
        else: 
            bst2.right = mergeBSTs(bst1, bst2.right)
            return bst2
    

    And the equivalent Fortran function:

    subroutine mergeBSTs(bst1, bst2, result)
        type(node), intent(in) :: bst1, bst2
        type(node), intent(out) :: result
        
        if (.not. bst1%exists) then
            result => bst2
            return
        else if (.not. bst2%exists) then
            result => bst1
            return    
        end if
        
        if (bst1%value < bst2%value) then
            call mergeBSTs(bst1%right, bst2, result%right)
            result => bst1
        else
            call mergeBSTs(bst1, bst2%right, result%right) 
            result => bst2
        end if
    end subroutine mergeBSTs
    

    Here I have defined a Node type in Fortran to represent the BST nodes:

    type node
       integer :: value
       type(node), pointer :: left, right
       logical :: exists 
    end type node
    

    Hope this helps! Let me know if you have any other questions.

Responses were produced in different, uncontrolled contexts (system prompts, settings, prior turns). This is not a benchmark.