// 返回最后一个关联节点 private Node findLastNode(T data, boolean searchStop){ if (this.getRoot() == null) thrownew RuntimeException("node root data is null"); Node current = this.getRoot(); for (;;) { if (current.getData() == null) thrownew RuntimeException("node data is null");
switch (current.getData().compareTo(data)){ case1: if (current.getLeft() == null) return current; current = current.getLeft(); break; case0: if (searchStop) return current; case -1: if(current.getRight() == null) return current; current = current.getRight(); break; default: thrownew RuntimeException("undefined number of type"); } } } // -------------------- 查找 // 查找目标节点 public Node find(T data){ if (data == null) thrownew IllegalArgumentException("data is null");
// 前序遍历 public List perorder(){ List list = new ArrayList(this.getNodeCount()); this.traverseTree(this.getRoot(), list, newint[] {1, 2, 3}); return list; }
// 前序遍历 public List inorder(){ List list = new ArrayList(this.getNodeCount()); this.traverseTree(this.getRoot(), list, newint[] {2, 1, 3}); return list; }
// 后序遍历 public List postorder(){ List list = new ArrayList(this.getNodeCount()); this.traverseTree(this.getRoot(), list, newint[] {2, 3, 1}); return list; }
// 根据规则读取数据 privatevoidtraverseTree(Node<T> current, List list, int[] order){ for (int i = 0; i < order.length; i++) { switch (order[i]){ case1: list.add(current); break; case2: if (current.getLeft() != null) this.traverseTree(current.getLeft(), list, order); break; case3: if (current.getRight() != null) this.traverseTree(current.getRight(), list, order); break; default: thrownew RuntimeException("undefined order type"); } } } // -------------------- /遍历
// -------------------- 演示 publicstaticvoidmain(String[] args){ BinartTree<Integer> tree = new BinartTree<>(); tree.add(90) .add(50).add(150) .add(20).add(75).add(95) .add(175).add(5).add(25) .add(66).add(80).add(111) .add(166).add(200).add(20);