📜  门| GATE-CS-2014-(Set-3)|问题2(1)

📅  最后修改于: 2023-12-03 15:28:44.106000             🧑  作者: Mango

GATE-CS-2014-(Set-3) Problem 2

This is a problem from the Graduate Aptitude Test in Engineering (GATE) in Computer Science conducted by the Indian Institute of Technology (IIT) in 2014. It tests the knowledge of programming concepts and algorithms.

Problem Statement

Consider the following types:

type node = null | {left : node, data : int, right : node}; 
type btree = node;
type alist = (int * int) list;

Consider the following function 'convert' that converts a binary tree of type 'btree' to an 'alist' of type 'alist'.

let rec convert (t : btree) : alist = 
 match t with
 | null -> []
 | {left=l , data=(_,k), right=r} -> (convert l)@[(k,1)]@(convert r)

Do the following: (i) Write down the types of the input and output of the function 'convert', and explain briefly what the function does. (ii) Write down the format of representing the binary tree using type 'btree', and represent the following binary tree using this format:

        5
       / \
      3   7
         / \
        6   8

(iii) What will be the result of the following expression?

convert( {left={left=null, data=(1,2), right=null}, data=(3,4), right={left=null, data=(5,6), right=null} } ) 
Solution
Part (i)

The function 'convert' takes a binary tree of type 'btree' as an input and returns an association list of type 'alist'. The function recursively traverses the binary tree and converts each node to a pair of integers in the form (data of node,1), where 1 denotes the frequency of occurrence of the node. The resulting association list contains all such pairs in the in-order traversal of the binary tree.

Part (ii)

The binary tree can be represented using the type 'btree' as follows:

{ 
  left={left=null , data=(3,1), right=null}, 
  data=(5,1), 
  right={left={left=null, data=(6,1), right=null}, data=(7,1), right={left=null, data=(8,1), right=null}} 
} 
Part (iii)

The expression convert( {left={left=null, data=(1,2), right=null}, data=(3,4), right={left=null, data=(5,6), right=null} } ) evaluates to [(1,1); (3,1); (5,1)], which represents the in-order traversal of the binary tree.

Code Snippet
type node = null | {left : node, data : int, right : node}; 
type btree = node;
type alist = (int * int) list;

let rec convert (t : btree) : alist = 
  match t with
  | null -> []
  | {left=l , data=(_,k), right=r} -> (convert l)@[(k,1)]@(convert r)

let tree = { 
  left={left=null , data=(3,1), right=null}, 
  data=(5,1), 
  right={left={left=null, data=(6,1), right=null}, data=(7,1), right={left=null, data=(8,1), right=null}} 
}

let result = convert tree