Amazon Interview Question
SDE-2sCountry: United States
Interview Type: In-Person
The question isn't clear - Assuming
1. We are talking about node values, rather than length.
2. Parent is fixed
3. Find the absolute max difference
So, I would use level order traversal of the tree (Similar to BFS) and for every new node evaluate the difference of node with its parent (node.value - parent.value) and check update the max difference until the subtree is exhausted
import java.util.Set;
import java.util.HashSet;
import java.util.PriorityQueue;
import java.util.Comparator;
public class NodeMaxDifference
{
PriorityQueue<TreeNode> maxq = null;
PriorityQueue<TreeNode> minq = null;
int diff = Integer.MIN_VALUE;
public NodeMaxDifference()
{
this.maxq = new PriorityQueue<>(10, new Comparator<TreeNode>(){
public int compare(TreeNode a, TreeNode b)
{
return Integer.compare(b.val, a.val);
}
});
this.minq = new PriorityQueue<>(10, new Comparator<TreeNode>(){
public int compare(TreeNode a, TreeNode b)
{
return Integer.compare(a.val, b.val);
}
});
}
public static void main(String[] args)
{
NodeMaxDifference n = new NodeMaxDifference();
TreeNode root = new TreeNode(1);
root.left = new TreeNode(2);
root.right = new TreeNode(3);
root.left.left = new TreeNode(9);
root.right.left = new TreeNode(7);
n.dfs(root);
System.out.println(n.diff);
}
public void dfs(TreeNode node)
{
helper(node);
}
private void helper(TreeNode root)
{
if(root==null)
return;
maxq.offer(root);
minq.offer(root);
if(maxq.peek().val - minq.peek().val > diff)
diff = maxq.peek().val - minq.peek().val;
helper(root.left);
helper(root.right);
maxq.remove(root);
minq.remove(root);
}
}
class TreeNode
{
int val;
TreeNode left;
TreeNode right;
TreeNode(int val)
{
this.val = val;
}
@Override
public boolean equals(Object o)
{
if(o instanceof TreeNode)
{
TreeNode temp = (TreeNode)o;
if(this==null && temp == null)
return true;
if(this==null || temp== null)
return false;
return this.val == temp.val;
}
else
{
return false;
}
}
@Override
public int hashCode()
{
return (this.val+"").hashCode();
}
public String toString()
{
return this.val+"";
}
}
I assume it can be any parent - child pair. I.e. for every node we find max diff (in value) with all of the nodes forming the subtree of the node.
My idea is to find the min and max values of the node's children. Max diff should be produced by either min or max of the children and the node's value.
- Alex November 17, 2017