|
| 1 | +import java.io.File; |
| 2 | +import java.io.FileWriter; |
| 3 | +import java.io.IOException; |
| 4 | +import org.apache.batik.dom.GenericDOMImplementation; |
| 5 | +import org.apache.batik.svggen.SVGGraphics2D; |
| 6 | +import org.w3c.dom.DOMImplementation; |
| 7 | +import org.w3c.dom.Document; |
| 8 | + |
| 9 | +class TreeNode { |
| 10 | + int data; |
| 11 | + TreeNode left; |
| 12 | + TreeNode right; |
| 13 | + |
| 14 | + public TreeNode(int data) { |
| 15 | + this.data = data; |
| 16 | + this.left = null; |
| 17 | + this.right = null; |
| 18 | + } |
| 19 | + |
| 20 | + public void insert(int data) { |
| 21 | + if (data < this.data) { |
| 22 | + if (this.left == null) { |
| 23 | + this.left = new TreeNode(data); |
| 24 | + } else { |
| 25 | + this.left.insert(data); |
| 26 | + } |
| 27 | + } else { |
| 28 | + if (this.right == null) { |
| 29 | + this.right = new TreeNode(data); |
| 30 | + } else { |
| 31 | + this.right.insert(data); |
| 32 | + } |
| 33 | + } |
| 34 | + } |
| 35 | +} |
| 36 | + |
| 37 | +public class BinaryTreeSVGExporter { |
| 38 | + public static void export(TreeNode root, String filename) throws IOException { |
| 39 | + DOMImplementation domImpl = GenericDOMImplementation.getDOMImplementation(); |
| 40 | + Document doc = domImpl.createDocument(null, "svg", null); |
| 41 | + SVGGraphics2D svg = new SVGGraphics2D(doc); |
| 42 | + |
| 43 | + // Traverse the tree and draw the nodes and edges |
| 44 | + traverse(root, svg, 100, 50, 50); |
| 45 | + |
| 46 | + // Write the SVG file |
| 47 | + File file = new File(filename); |
| 48 | + FileWriter fw = new FileWriter(file); |
| 49 | + svg.stream(fw, true); |
| 50 | + } |
| 51 | + |
| 52 | + private static void traverse(TreeNode node, SVGGraphics2D svg, int x, int y, int dx) { |
| 53 | + if (node == null) { |
| 54 | + return; |
| 55 | + } |
| 56 | + |
| 57 | + // Draw the node |
| 58 | + svg.drawOval(x - 10, y - 10, 20, 20); |
| 59 | + svg.drawString(String.valueOf(node.data), x - 4, y + 4); |
| 60 | + |
| 61 | + // Draw the left child and edge |
| 62 | + if (node.left != null) { |
| 63 | + svg.drawLine(x, y, x - dx, y + 50); |
| 64 | + traverse(node.left, svg, x - dx, y + 50, dx / 2); |
| 65 | + } |
| 66 | + |
| 67 | + // Draw the right child and edge |
| 68 | + if (node.right != null) { |
| 69 | + svg.drawLine(x, y, x + dx, y + 50); |
| 70 | + traverse(node.right, svg, x + dx, y + 50, dx / 2); |
| 71 | + } |
| 72 | + } |
| 73 | + |
| 74 | + public static void main(String[] args) { |
| 75 | + TreeNode root = new TreeNode(10); |
| 76 | + root.insert(5); |
| 77 | + root.insert(15); |
| 78 | + root.insert(3); |
| 79 | + root.insert(7); |
| 80 | + root.insert(13); |
| 81 | + root.insert(17); |
| 82 | + |
| 83 | + try { |
| 84 | + BinaryTreeSVGExporter.export(root, "binary_tree.svg"); |
| 85 | + } catch (IOException e) { |
| 86 | + e.printStackTrace(); |
| 87 | + } |
| 88 | + } |
| 89 | +} |
0 commit comments