Interview Question
Country: United States
Interview Type: Phone Interview
I think we can do it by reverse inorder traversal
/* Function for reverse inorder */
int data;
void revInorder(struct node* root, int kthLargest)
{
static int count = 0;
if(root == NULL)
{
return;
}
revInorder(root->right, kthLargest);
count++;
if(count == kthLargest)
{
data = root->data;
return;
}
revInorder(root->left, kthLargest);
}
1. It doesn't compile cause there is no final return instruction.
2. It doesn't work cause it doesn't check the return value from the recursive calls.
3. It scans the whole tree, instead of stopping after finding the node.
fail.
public static final Node secondLargest(Node root) {
if(root == null || root.right == null) {
return null;
}
Node next = root.right;
Node larger = next.right;
if( larger != null) {
return secondLargest(next);
} else {
return root;
}
}
Consider a 2 node tree which has root and left child only.For your solution it will return NULL
Idea:
1. Find the right most node. If the right most node has no left child, then its parent is second largest.
2. If the right most node has a left child, then the largest in left part will be the second largest.
public static Node SecondLargest(Node root)
{
if(root==null)||(root.left==null&&root.right==null)
return null;
Node large=root,secLarge;
while(large.right!=null)
{
large=large.right;
secLarge=large;
}
if(large.left==null)
return secLarge;
return Largest(large);
}
public static Node Largest(Node root)
{
while(root.right!=null)
root=root.right;
return root;
}
1. Go to the right most node
2.1 if it has left child , then the biggest value from its left child is the result
2.2 if not then the result is its parent.
Important : verify if the tree has at least 2 values
private static Node secondLargest(Node root) {
if (root == null || root.left == null && root.right == null) return null;
Node curr=null,prev=null;
if (root.right == null) {
curr= root.left;
while (curr.right != null)
curr = curr.right;
return curr;
}else{
curr=root;
while(curr.right!=null){
prev=curr;
curr=curr.right;
}
return prev;
}
}
if largest element has no child then its parent.
- awasthi.manoj January 23, 2013if largest element has left child then left child.