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
| package com.tree.thread; public class ThreadTree { private Node root; private Node pre = null; public ThreadTree() { this.root = null; this.pre = null; } public ThreadTree(int[] data) { this.pre = null; this.root = createTree(data, 0); }
public Node createTree(int[] data, int index) { if (index >= data.length) { return null; } Node node = new Node(data[index]); node.setLeft(createTree(data, 2 * index + 1)); node.setRight(createTree(data, 2 * index + 2)); return node; }
public void inThread(Node root) { if (root != null) { inThread(root.getLeft()); if (null == root.getLeft()) { root.setLeftIsThread(true); root.setLeft(pre); } if (pre != null && null == pre.getRight()) { pre.setRightIsThread(true); pre.setRight(root); } pre = root; inThread(root.getRight()); } }
public void inThreadList(Node root) { if (root == null) { return; } while (root != null && !root.isLeftIsThread()) { root = root.getLeft(); } while (root != null) { System.out.print(root.getData() + ","); if (root.isRightIsThread()) { root = root.getRight(); } else { root = root.getRight(); while (root != null && !root.isLeftIsThread()) { root = root.getLeft(); } } } }
public void inList(Node root) { if (root != null) { inList(root.getLeft()); System.out.print(root.getData() + ","); inList(root.getRight()); } } public Node getRoot() { return root; } public void setRoot(Node root) { this.root = root; } }
JAVA
|