## Amazon Interview Question for SDE1s

Country: India
Interview Type: In-Person

Comment hidden because of low score. Click to expand.
0
of 0 vote

You need to define pruning, as it can mean a lot of things. In the most general sense, you can be pruning either the breadth or the height of the tree.

The most common is to prune all the leaf nodes. Something like this might work:

``````void prune(Node *n, Node *parent, bool direction) {
if(n=NULL || (parent==NULL && n.left == NULL && n.right == NULL))
return;        // you are pruning the root
if(n.left == NULL && n.right == NULL)
delete n;
if (direction == false) parent.left = NULL;
else if (direction ==true) parent.right = NULL;
else
prune(n.left, n, false);
prune(n.right, n, true);
}``````

Comment hidden because of low score. Click to expand.
0
of 0 vote

deleting a node directly would result in dangling pointers, so first check if any of the child node is leaf or not and if leaf then remove the child reference and free memory.

``````void prune(Node *root) {
if(root == NULL) return;
if(root->left != NULL) {
Node *leftChild = root->left;
if(leftChild->left == NULL && leftChild->right == NULL) {
root->left = NULL;
free(leftChild);
}
}
if(root->right != NULL) {
Node *rightChild = root->right;
if(rightChild->left == NULL && rightChild->right == NULL) {
root->left = NULL;
free(rightChild);
}
}
prune(root->left);
prune(root->right);
}``````

Name:

Writing Code? Surround your code with {{{ and }}} to preserve whitespace.

### Books

is a comprehensive book on getting a job at a top tech company, while focuses on dev interviews and does this for PMs.

### Videos

CareerCup's interview videos give you a real-life look at technical interviews. In these unscripted videos, watch how other candidates handle tough questions and how the interviewer thinks about their performance.