The task is to return all root-to-leaf paths, given a binary tree (from leetcode).
This is my approach.
- Take a helper array and a counter, keeping track of what has been traversed so far. If it is leaf node, print all till that point.
- Reduce counter.
Please suggest improvements, if any.
import java.util.LinkedList;
import java.util.List;
public class LeafNode {
private List<String> list;
private int count = -1;//counts no. of element in print array
private int[] printArray;// a helper array class to print nodes
public List<String> binaryTreePaths(TreeNode root) {
list = new LinkedList<>();
if(root == null){
return list;
}
printArray = new int[10000];// assuming the maximum size will be less than 10000
printList(root);
return list;
}
private void printList(TreeNode root) {
printArray[++count] = root.val;
if(root.left == null && root.right == null) {
printTillNow();
} else{
if(root.left != null) {
printList(root.left);
}
if(root.right != null){
printList(root.right);
}
}
--count;
}
//just prints all the nodes so far
private void printTillNow() {
if(count < 0){
return;
}
StringBuilder sb = new StringBuilder();
int i =0;
for(i = 0; i<count; i++){
sb.append(printArray[i]);
sb.append("->");
}
sb.append(printArray[i]);
list.add(sb.toString());
}
}