1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
|
import matplotlib.pyplot as plt
import networkx as nx
# Tree class definition
class Tree:
def __init__(self, value, left=None, right=None):
self.value = value
self.left = left
self.right = right
# Solution class
class Solution:
def __init__(self):
self.graph = nx.DiGraph()
def build_graph(self, node, parent=None):
"""
Recursively adds nodes and edges to the graph for graphical representation.
"""
if not node: # If the node is None, return
return
self.graph.add_node(str(node.value)) # Add current node
if parent:
self.graph.add_edge(str(parent.value), str(node.value)) # Connect to parent
# Recursively add left and right children
self.build_graph(node.left, node)
self.build_graph(node.right, node)
def draw_tree(self, tree):
"""
Generate and display graphical representation of the given tree.
"""
self.build_graph(tree) # Build graph structure from tree
# Position nodes using GraphViz layout
pos = nx.nx_agraph.graphviz_layout(self.graph, prog="dot")
nx.draw(self.graph, pos, with_labels=True, arrows=False, node_size=2000, node_color="skyblue")
plt.show()
# Example usage:
tree1 = Tree('+', Tree(1), Tree('*', Tree(2), Tree(3)))
tree2 = Tree('-', Tree('/', Tree(8), Tree(4)), Tree(7))
solution = Solution()
solution.draw_tree(tree1) # Graphical representation of tree1
solution.draw_tree(tree2) # Graphical representation of tree2
|