Consider an implementation of binary trees with Scheme lists, as in the followin
ID: 3884466 • Letter: C
Question
Consider an implementation of binary trees with Scheme lists, as in the following example: (define T '(13 (5 (1 () ()) (8 () (9 ()()))) (22 (17 () ()) (25 () ())))) Before proceeding, it may be useful to define three auxiliary functions (val T), (left T) and (right T), which return the value in the root of tree T, its left subtree and its right subtree, respectively. (a) Write a recursive function (tree-member? V T), which determines whether V appears as an element in the tree T. The following example illustrates the use of this function: > (tree-member? 17 T) #t (b) Write a recursive function (preorder T), which returns the list of all elements in the tree T corresponding to a preorder traversal of the tree. The following example illustrates the use of this function: > (preorder T) (13 5 1 8 9 22 17 25) (c) Write a recursive function (inorder T), which returns the list of all elements in the tree T corresponding to an inorder traversal of the tree. The following example illustrates the use of this function: > (inorder T) (1 5 8 9 13 17 22 25)Explanation / Answer
Search :
public Node search(Node root, int key)
{
// Base Cases: root is null or key is present at root
if (root==null || root.key==key)
return root;
// val is greater than root's key
if (root.key > key)
return search(root.left, key);
// val is less than root's key
return search(root.right, key);
}
Postorder traversal :
void printPostorder(Node node)
{
if (node == null)
return;
// first recur on left subtree
printPostorder(node.left);
// then recur on right subtree
printPostorder(node.right);
// now deal with the node
System.out.print(node.key + " ");
}
Preorder
/* Given a binary tree, print its nodes in preorder*/
void printPreorder(Node node)
{
if (node == null)
return;
/* first print data of node */
System.out.print(node.key + " ");
/* then recur on left sutree */
printPreorder(node.left);
/* now recur on right subtree */
printPreorder(node.right);
}