Interview Question


Country: United States




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

Node * getNextLeastNode( Node *root, int item)
{
	Node *cur = NULL, *prev = NULL;
	if( root == NULL)
		return NULL;
	cur = DFSBST(root, item);
	if(cur != NULL)
		cur = cur ->left;
	while ( cur != NULL )
	{
		prev = cur;
		cur = cur->right;
	}
	return prev;

}
Node* DFSBST( Node *root, int item)
{
	
	Stack stack;
	Push( &stack, root);
	while( Pop( &stack, &root) )
	{
		if( root -> data == item )
			return root ;
		if (root -> right )
			Push( &stack, root ->right );
		if (root -> left )
			Push( &stack, root ->left );
	}
	return NULL;
}

- Anonymous February 20, 2014 | Flag Reply
Comment hidden because of low score. Click to expand.
0
of 0 vote

For a given subtree, there are 3 cases:
(1)root is NULL, then no such node in this subtree
(2)root->val < K, then the result might be in the root's right subtree or just root itself
(3)root->val >= K, then the result could only be in the root's left subtree
Following is C code:

TreeNode* findNextSmallerInBST(TreeNode* root, int K)
{
	if(root == NULL) return NULL;
	else if(root->val < K){
		TreeNode* t = findNextSmallerInBST(root->right, K);
		return t != NULL ? t : root;
	}
	else return findNextSmallerInBST(root->left, K);
}

- uuuouou February 20, 2014 | Flag Reply
Comment hidden because of low score. Click to expand.
0
of 0 vote

Trace from the left child starting from the root until there's no left child. This node the minimum of the tree. If the node has right child, the second minimum is the minimum of the left child sub tree. Otherwise, he second minimum is its parent.

- Westlake February 20, 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