NVIDIA Interview Question
Software Engineer InternsTeam: Driver Development
Country: United States
Interview Type: Phone Interview
First attempt with original BST initialization and a display function to check accuracy after mirorring.
The code does not create a new BST yet.
#include <stdlib.h>
#include <iostream>
#include <stdio.h>
struct Node;
Node * mirrorTree(Node * root);
//*****Utils Functions declarations****
Node * newNode (int value); //create a new node
int max (int left_hand, int right_hand); //return the max value between two ints
void testDisplayTree (Node * root); //display the whole tree
void testDisplayNode (Node * node); //display a node and its two children
//**************************************
struct Node {
int value;
Node * left;
Node * right;
};
int main (int argc, char ** argv) {
//create the binary tree
/*
Tree
1
/ \
2 3
/\ /\
4 5 6 7
\
9
*/
Node * root = new Node;
root->value = 1;
root->left = newNode(2);
root->right = newNode(3);
root->left->left = newNode(4);
root->left->right = newNode(5);
root->left->left->right = newNode(9);
root->right->left = newNode(6);
root->right->right = newNode(7);
//test the layout of tree
testDisplayTree (root);
mirrorTree(root);
printf ("After Mirror\n");
//check if values where swapped
testDisplayTree (root);
}
Node * mirrorTree(Node * root) {
if (root == NULL) {
return NULL;
}
if (root->left == NULL && root->right == NULL) {
return root;
}
Node * left = mirrorTree (root->left);
Node * right = mirrorTree (root->right);
root->left = right;
root->right = left;
return root;
}
/********Utils functions *******/
//add a new node
Node * newNode (int value) {
Node * node = new Node;
node->value = value;
node->left = NULL;
node->right = NULL;
return node;
}
//return the greatest int
int max (int left_hand, int right_hand) {
if (left_hand >= right_hand)
return left_hand;
else
return right_hand;
}
//display a node and its children
void testDisplayNode(Node * node) {
printf ("node with value: %u, left child value: %d, right child value:%d\n",
node->value,
node->left !=NULL?node->left->value:-1,
node->right!=NULL?node->right->value:-1);
}
//display the whole tree
void testDisplayTree (Node * root) {
if (root == NULL) {
return;
}
testDisplayNode(root);
testDisplayTree (root->left);
testDisplayTree (root->right);
}
- Anonymous February 12, 2014