DFS for Ternary Tree

Amit Gupta
1 min readMar 30, 2021
public static String[] ternaryTreePaths(Node root) {
if(root== null ) return null;
ArrayList<String> al = new ArrayList<String>();
ArrayList<String> res = new ArrayList<String>();
dfs(root, al, res);
return res.toArray(new String[res.size()]);
}

public static void dfs(Node root, ArrayList<String> list, ArrayList<String> res){
boolean isNoChild = true;
for(Node child : root.children){
if(child!=null){
isNoChild= false;
}
}
if(isNoChild){
StringBuilder sb = new StringBuilder();
for(String val : list)
sb.append(val + "->");
sb.append(root.val);
if(sb.length()>1){
res.add(sb.toString());
}
return;
}
list.add(Integer.toString(root.val));

for(Node child: root.children){
if(child!=null)
dfs(child, list,res);
}
if(list.size()>0){
list.remove(list.size()-1);
}

}

The above algorithm tells how we can traverse through ternary tree or any tree using dfs technique. We simply need to put for loop for all children of a node where we generally use node.left and node.right for binary tree.

Whenever we want to terminate condition for which there is no children of a node then also use for loop to check whether children list is null or list is empty.

--

--