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);
}

- AK February 27, 2014 | Flag Reply
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);
}

- cptjack March 12, 2014 | Flag Reply


Add a Comment
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.

Learn More

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.

Learn More

Resume Review

Most engineers make critical mistakes on their resumes -- we can fix your resume with our custom resume review service. And, we use fellow engineers as our resume reviewers, so you can be sure that we "get" what you're saying.

Learn More

Mock Interviews

Our Mock Interviews will be conducted "in character" just like a real interview, and can focus on whatever topics you want. All our interviewers have worked for Microsoft, Google or Amazon, you know you'll get a true-to-life experience.

Learn More