|
| 1 | +package datastructure; |
| 2 | + |
| 3 | +import java.io.*; |
| 4 | +import java.util.ArrayList; |
| 5 | +import java.util.List; |
| 6 | + |
| 7 | +/** |
| 8 | + * @author yangqc |
| 9 | + */ |
| 10 | +public class IndexTree { |
| 11 | + static private int Sn = -1; |
| 12 | + static private Node root; |
| 13 | + |
| 14 | + static private class Node implements Serializable { |
| 15 | + int data; |
| 16 | + transient Node left; |
| 17 | + transient Node right; |
| 18 | + int l = -1, r = -1; |
| 19 | + |
| 20 | + public Node(int data, Node l, Node r) { |
| 21 | + this.data = data; |
| 22 | + this.left = l; |
| 23 | + this.right = r; |
| 24 | + } |
| 25 | + |
| 26 | + public int write(ObjectOutputStream out) throws IOException { |
| 27 | + if (left != null) { |
| 28 | + l = left.write(out); |
| 29 | + } |
| 30 | + if (right != null) { |
| 31 | + r = right.write(out); |
| 32 | + } |
| 33 | + Sn++; |
| 34 | + out.writeObject(this); |
| 35 | + return Sn; |
| 36 | + } |
| 37 | + |
| 38 | + private void init(List<Node> list) { |
| 39 | + if (l != -1) { |
| 40 | + left = list.get(l); |
| 41 | + left.init(list); |
| 42 | + } |
| 43 | + if (r != -1) { |
| 44 | + right = list.get(r); |
| 45 | + right.init(list); |
| 46 | + } |
| 47 | + } |
| 48 | + |
| 49 | + @Override |
| 50 | + public String toString() { |
| 51 | + StringBuilder sb = new StringBuilder(); |
| 52 | + sb.append(data + " "); |
| 53 | + if (left != null) { |
| 54 | + sb.append(left); |
| 55 | + } |
| 56 | + if (right != null) { |
| 57 | + sb.append(right); |
| 58 | + } |
| 59 | + return sb.toString(); |
| 60 | + } |
| 61 | + } |
| 62 | + |
| 63 | + static public void read(ObjectInputStream in) { |
| 64 | + List<Node> list = new ArrayList<>(); |
| 65 | + Node n; |
| 66 | + try { |
| 67 | + while (((n = (Node) in.readObject()) != null)) { |
| 68 | + list.add(n); |
| 69 | + } |
| 70 | + } catch (Exception e) { |
| 71 | + e.printStackTrace(); |
| 72 | + } |
| 73 | + root = list.get(list.size() - 1); |
| 74 | + root.init(list); |
| 75 | + } |
| 76 | + |
| 77 | + public static void main(String[] args) throws IOException { |
| 78 | + // 构造一棵二叉树 |
| 79 | + /* |
| 80 | + * 1 2 3 4 5 6 |
| 81 | + */ |
| 82 | + Node n6 = new Node(6, null, null); |
| 83 | + Node n4 = new Node(4, n6, null); |
| 84 | + Node n5 = new Node(5, null, null); |
| 85 | + Node n2 = new Node(2, n4, n5); |
| 86 | + Node n3 = new Node(3, null, null); |
| 87 | + Node n1 = new Node(1, n2, n3); |
| 88 | + root = n1; |
| 89 | + System.out.println(root); |
| 90 | + ObjectOutputStream out = new ObjectOutputStream(new FileOutputStream("abc.ser")); |
| 91 | + root.write(out); |
| 92 | + out.close(); |
| 93 | + ObjectInputStream in = new ObjectInputStream(new FileInputStream("abc.ser")); |
| 94 | + read(in); |
| 95 | + in.close(); |
| 96 | + System.out.println(root); |
| 97 | + } |
| 98 | +} |
0 commit comments