Given a binary search tree, design an algorithm which creates a linked list of all thenodes at each depth (eg, if you have a tree with depth D, you’ll have D linked lists)
==============
Analysis:
Data structures has been given, using linked lists to contain the tree nodes in each level, returning the set of these linked lists as an Array list.
This problem is level order tree traversal, in which we can utilize recursive approach, with the parameter "depth". Therefore, the basic process of the solution is to traverse all the tree nodes one by one and add it to the corresponding linked list in the result set.
public class Answer {
public static ArrayList<LinkedList<TreeNode>> solution(TreeNode root){
ArrayList<LinkedList<TreeNode>> rs = new ArrayList<LinkedList<TreeNode>>();
helper(rs, root, 0);
return rs;
}
public static void helper(ArrayList<LinkedList<TreeNode>> rs, TreeNode node, int depth){
if(node == null) return;
// get linked list for current the level current node
LinkedList<TreeNode> treeNodeList = null;
if(depth+1>rs.size()) {
treeNodeList = new LinkedList<TreeNode>();
rs.add(depth, treeNodeList);
}
else{
treeNodeList = rs.get(depth);
}
treeNodeList.add(treeNodeList.size(), node);
if(node.left!=null) helper(rs, node.left, depth+1);
if(node.right!=null) helper(rs, node.right, depth+1);
}
}
Note that my solution is different from the one descried in the book. Solution in the book uses iteration approach rather than recursive approach, adding nodes in the tree level by level (constructing the linked list one by one).
public static ArrayList<LinkedList<TreeNode>> findLevelLinkList(TreeNode root) {
int level = 0;
ArrayList<LinkedList<TreeNode>> result = new ArrayList<LinkedList<TreeNode>>();
LinkedList<TreeNode> list = new LinkedList<TreeNode>();
list.add(root);
result.add(level, list);
while (true) {
list = new LinkedList<TreeNode>();
for(int i = 0; i < result.get(level).size(); i++){
TreeNode n = (TreeNode) result.get(level).get(i);
if(n != null) {
if(n.left != null) list.add(n.left);
if(n.right!= null) list.add(n.right);
}
}
if (list.size() > 0) {
result.add(level + 1, list);
}
else {
break;
}
level++;
}
return result;
}
Another thing draws my attention is that linked list using in these solutions is different from the one we defined in the linked list problems. In the linked list problems, we defined list node rather than using link lists, and we could extract a list node we want by only checking each node from the header node to the target node. While in java data structure, we can directly operate on an list node by giving the index of the list node.