tree_service.py 2.4 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889
  1. from service.base_service import BaseService
  2. class TreeNode:
  3. def __init__(self, value):
  4. self.value = value
  5. self.children = []
  6. class TreeService(BaseService):
  7. def __init__(self):
  8. pass
  9. @classmethod
  10. def build_tree_from_lists(cls, lists: list) -> tuple:
  11. """
  12. build tree from lists,
  13. [1,2,3], [1,2,4], [1,5,6]-->
  14. 1
  15. / \
  16. 2 5
  17. / \ /
  18. 3 4 6
  19. :param lists:
  20. :return:
  21. """
  22. root = TreeNode(0)
  23. for lst in lists:
  24. current_node = root
  25. for val in lst:
  26. # search same value child node
  27. child_node = None
  28. for child in current_node.children:
  29. if child.value == val:
  30. child_node = child
  31. break
  32. # can not get child node, then create a new child
  33. if child_node is None:
  34. child_node = TreeNode(val)
  35. current_node.children.append(child_node)
  36. # move to child node
  37. current_node = child_node
  38. return root
  39. @classmethod
  40. def get_value_list_from_tree(cls, tree_node: TreeNode) -> tuple:
  41. """
  42. get value list from a tree's node
  43. :param tree_node:
  44. :return:
  45. """
  46. result_list = []
  47. if tree_node:
  48. result_list.append(tree_node.value)
  49. for child in tree_node.children:
  50. result_list += cls.get_value_list_from_tree(child)
  51. return result_list
  52. @classmethod
  53. def get_node_list_from_tree(cls, tree_node:TreeNode) -> tuple:
  54. """
  55. get all node list from tree
  56. :param tree_node:
  57. :return:
  58. """
  59. result_list = []
  60. if tree_node:
  61. result_list.append(tree_node)
  62. for child in tree_node.children:
  63. result_list += cls.get_node_list_from_tree(child)[1]
  64. return True, result_list
  65. @classmethod
  66. def get_leaf_value_list_from_tree(cls, tree_node: TreeNode) -> tuple:
  67. """
  68. get leaf node value list
  69. :param tree_node:
  70. :return:
  71. """
  72. result_list = []
  73. flag, node_list = cls.get_node_list_from_tree(tree_node)
  74. for node0 in node_list:
  75. if not node0.children:
  76. result_list.append(node0.value)
  77. return True, result_list
  78. tree_service_ins = TreeService()