I want you to pick my code apart and give me some feedback on how I could make it better or simpler. This code converts a binary tree to a doubly linked list (in order).
public class BinaryTreeToLinkedList {
private TreeNode root;
private static class TreeNode {
TreeNode left;
TreeNode right;
int item;
public TreeNode(TreeNode left, TreeNode right, int item) {
this.left = left;
this.right = right;
this.item = item;
}
}
private TreeNode appendDLL (TreeNode left, TreeNode right) {
if (left == null) return right;
if (right == null) return left;
// get last element of left linkedlist
TreeNode leftLast = left.left;
TreeNode rightLast = right.left;
leftLast.right = right;
right.left = leftLast;
// now we form the list into circular again.
rightLast.right = left;
left.left = rightLast;
return left;
}
private TreeNode postOrder(TreeNode node) {
if (node == null) {
return null;
}
TreeNode leftList = postOrder(node.left);
TreeNode rightList = postOrder(node.right);
// convert the current node into doubly LL
node.left = node;
node.right = node;
// hook current node.
leftList = appendDLL (leftList, node);
// hook right side linkedlist
leftList = appendDLL (leftList, rightList);
return leftList;
}
public void convertToLinkedList() {
root = postOrder(root);
}
}