File size: 4,507 Bytes
3c12af9
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
import graphviz
import json
from tempfile import NamedTemporaryFile
import os

def generate_binary_tree_diagram(json_input: str, output_format: str) -> str:
    """
    Generates a binary tree diagram from JSON input.

    Args:
        json_input (str): A JSON string describing the binary tree structure.
                          It must follow the Expected JSON Format Example below.

    Expected JSON Format Example:
    {
      "root": {
        "id": "root",
        "label": "50",
        "left": {
          "id": "left_1",
          "label": "30",
          "left": {
            "id": "left_2",
            "label": "20"
          },
          "right": {
            "id": "right_2",
            "label": "40"
          }
        },
        "right": {
          "id": "right_1",
          "label": "70",
          "left": {
            "id": "left_3",
            "label": "60"
          },
          "right": {
            "id": "right_3",
            "label": "80"
          }
        }
      }
    }

    Returns:
        str: The filepath to the generated PNG image file.
    """
    try:
        if not json_input.strip():
            return "Error: Empty input"
            
        data = json.loads(json_input)
        
        if 'root' not in data:
            raise ValueError("Missing required field: root")

        dot = graphviz.Digraph(
            name='BinaryTree',
            format='png',
            graph_attr={
                'rankdir': 'TB',        # Top-to-Bottom layout (vertical hierarchy)
                'splines': 'line',      # Straight lines
                'bgcolor': 'white',     # White background
                'pad': '0.5',           # Padding around the graph
                'nodesep': '0.8',       # Spacing between nodes
                'ranksep': '1.0'        # Spacing between levels
            }
        )
        
        base_color = '#19191a' # Hardcoded base color
        
        def add_binary_tree_nodes(node, current_depth=0):
            """
            Add binary tree nodes recursively with proper styling.
            """
            if not node:
                return
            
            node_id = node.get('id', f'node_{current_depth}')
            node_label = node.get('label', 'Node')
            
            # Calculate color opacity based on depth
            max_depth = 5  # Assume maximum depth for color calculation
            if current_depth >= max_depth:
                opacity = '80'  # Minimum opacity
            else:
                opacity_value = int(255 * (1.0 - (current_depth * 0.6 / max_depth)))
                opacity = format(opacity_value, '02x')
            
            node_color = f"{base_color}{opacity}"
            font_color = 'white' if current_depth < 3 else 'black'
            
            # Add the current node
            dot.node(
                node_id,
                node_label,
                shape='circle',
                style='filled',
                fillcolor=node_color,
                fontcolor=font_color,
                fontsize='14',
                width='0.8',
                height='0.8'
            )
            
            # Process left child
            left_child = node.get('left')
            if left_child:
                add_binary_tree_nodes(left_child, current_depth + 1)
                left_id = left_child.get('id', f'node_{current_depth + 1}_left')
                dot.edge(
                    node_id,
                    left_id,
                    color='#666666',
                    arrowsize='0.8'
                )
            
            # Process right child
            right_child = node.get('right')
            if right_child:
                add_binary_tree_nodes(right_child, current_depth + 1)
                right_id = right_child.get('id', f'node_{current_depth + 1}_right')
                dot.edge(
                    node_id,
                    right_id,
                    color='#666666',
                    arrowsize='0.8'
                )
        
        # Add binary tree nodes and edges recursively
        add_binary_tree_nodes(data['root'], current_depth=0)

        with NamedTemporaryFile(delete=False, suffix=f'.{output_format}') as tmp:
            dot.render(tmp.name, format=output_format, cleanup=True)
            return f"{tmp.name}.{output_format}"

    except json.JSONDecodeError:
        return "Error: Invalid JSON format"
    except Exception as e:
        return f"Error: {str(e)}"