Amazon Interview Question
Software Engineer / DevelopersCountry: United States
Interview Type: Phone Interview
I think it should be
{
void inOrder(node *root){
if (root==NULL) return;
inOrder(root->left);
if(last!=NULL){
last->next = root;
last= last->next;
}
last = root;
inOrder(root->right);
}
}
Assuming that the Tree structure could be changed. We can use a modified version of the Threaded binary tree. Here we are changing the 'right' TreeNode reference of a TreeNode. We pass on the last visited TreeNode through the recursion stack, and return the last visited TreeNode to the previous call of the recursion.
class TreeNode{
TreeNode left = null;
TreeNode right = null;
}
private TreeNode inOrderLLTransf(TreeNode root, TreeNode predec){
if(root == null){
return null;
}
if(root.left!= null){
predec = inOrderLLTransf(root.left, predec);
}
if(predec != null){
predec.right = root;
}
predec = root;
if(root.right != null){
predec = inOrderLLTransf(root.right,predec);
}
return predec;
}
public void transformTree(TreeNode root){
TreeNode lastVisited = inOrderLLTransf(root.right, null);
if(lastVisited == null){
//ERROR
}
}
This is the iterative solution using Stack in JAVA
public void flatten(TreeNode root) {
// Start typing your Java solution below
// DO NOT write main() function
if(root == null){
return;
}
Stack<TreeNode> stack = new Stack<TreeNode>();
stack.push(root);
TreeNode previous = null;
while(!stack.empty()){
TreeNode current = stack.pop();
if (current.right!=null) {
stack.push(current.right);
}
if (current.left!=null) {
stack.push(current.left);
}
current.left = null;
current.right = null;
if (current == root) {
previous = current;
}
else{
previous.right = current;
previous = current;
}
}
}
- Crazy Tesla January 24, 2013