Tree Generation by given string content using JAVA


/ Published in: Java
Save to your folder(s)

This is a java class to generate a tree by given string content


Copy this code and paste it in your HTML
  1. import java.util.ArrayList;
  2. import java.util.List;
  3.  
  4. /**
  5.  * To generate a tree by given string content
  6.  * @author MD. MUZAHIDUL ISLAM ([email protected])
  7.  * */
  8. public class TreeNode {
  9.  
  10. TreeNode parentNode;
  11. String content = "";
  12. String trace = "";
  13. List<TreeNode> childNodes = new ArrayList<TreeNode>();
  14. int depth = 0;
  15. int level = 0;
  16.  
  17. String options;
  18.  
  19. public static TreeNode root = null;
  20. public static List<TreeNode> leafs;
  21.  
  22.  
  23. public TreeNode(TreeNode parentNode, String content, String trace, int level, int depth, String options){
  24. this.parentNode = parentNode;
  25. this.content = content;
  26. this.trace =trace;
  27. this.level = level;
  28. this.depth = depth;
  29. this.options = options;
  30. if (level < depth) {
  31. createChild(options);
  32. }
  33. else {
  34. leafs.add(this);
  35. }
  36. }
  37.  
  38. public TreeNode(boolean isRoot, TreeNode parentNode, String content, String trace, int level, int depth, String options){
  39. if(isRoot){
  40. leafs = new ArrayList<TreeNode>();
  41. }
  42. this.parentNode = parentNode;
  43. this.content = content;
  44. this.trace =trace;
  45. this.level = level;
  46. this.depth = depth;
  47. this.options = options;
  48. if (level < depth) {
  49. createChild(options);
  50. }
  51. else {
  52. leafs.add(this);
  53. }
  54. }
  55.  
  56. public void createChild(String options) {
  57. for(char c : options.toCharArray()){
  58. childNodes.add(new TreeNode(this, ""+c, this.trace+c, this.level+1, this.depth, this.options));
  59. }
  60. }
  61. }

Report this snippet


Comments

RSS Icon Subscribe to comments

You need to login to post a comment.