Thanks for the solution. It's good to have you in the group.
Here is my solution:
package com.seabook.google.algorithm;
import java.util.ArrayList;
import java.util.List;
public class TreeMutation {
public static void main(String[] args) {
TreeMutation treeMutation = new TreeMutation();
TNode tree = treeMutation.createSampleTree();
List<TNode> nodes = new ArrayList<TNode>();
treeMutation.populateTree(tree, 0, nodes);
printTree(tree);
}
public TNode createSampleTree() {
TNode node1 = new TNode("1");
TNode node2 = new TNode("2");
TNode node3 = new TNode("3");
TNode node4 = new TNode("4");
TNode node5 = new TNode("5");
TNode node6 = new TNode("6");
TNode node7 = new TNode("7");
node1.left = node2;
//node1.right = node5;
node1.right = node3;
node2.left = node4;
node3.right = node5;
node5.left = node6;
node5.right = node7;
return node1;
}
public void populateTree(TNode tNode, int i, List<TNode> nodes) {
if (nodes.size() != 0 && i < nodes.size()) {
nodes.get(i).next = tNode;
nodes.set(i, tNode);
} else
nodes.add(tNode);
i++;
if (tNode.left != null) {
populateTree(tNode.left, i, nodes);
}
if (tNode.right != null) {
populateTree(tNode.right, i, nodes);
}
}
public static void printTree(TNode tree) {
String left = tree.left == null ? "null" : tree.left.label;
String right = tree.right == null ? "null" : tree.right.label;
String next = tree.next == null ? "null" : tree.next.label;
System.out.println(tree.label + " - [L:" + left + " R:"
+ right + " N:" + next + "]");
if (tree.left != null) {
printTree(tree.left);
}
if (tree.right != null) {
printTree(tree.right);
}
}
private class TNode {
TNode left;
TNode right;
TNode next;
String label;
public TNode(String label) {
this.label = label;
}
}
}