(1)二叉树
- package ChapterEight;
- class Tree {
- class Node {
- public long value;
- public Node leftChild;
- public Node rightChild;
- public Node(long value) {
- this.value = value;
- leftChild = null;
- rightChild = null;
- }
- }
- public Node root;
- public Tree() {
- root = null;
- }
- // 向树中插入一个节点
- public void insert(long value) {
- Node newNode = new Node(value);
- // 树是空的
- if (root == null)
- root = newNode;
- else {
- Node current = root;
- Node parentNode;
- while (true) {
- parentNode = current;
- if (value < current.value) {
- current = current.leftChild;
- // 要插入的节点为左孩子节点
- if (current == null) {
- parentNode.leftChild = newNode;
- return;
- }
- } else {
- // 要插入的节点为右孩子节点
- current = current.rightChild;
- if (current == null) {
- parentNode.rightChild = newNode;
- return;
- }
- }
- }
- }
- }
- // 先续遍历树中的所有节点
- public void preOrder(Node currentRoot) {
- if (currentRoot != null) {
- System.out.print(currentRoot.value + " ");
- preOrder(currentRoot.leftChild);
- preOrder(currentRoot.rightChild);
- }
- }
- // 中续遍历树中的所有节点
- public void inOrder(Node currentNode) {
- if (currentNode != null) {
- inOrder(currentNode.leftChild);
- System.out.print(currentNode.value + " ");
- inOrder(currentNode.rightChild);
- }
- }
- // 后续遍历树中的所有节点
- public void postOrder(Node currentNode) {
- if (currentNode != null) {
- postOrder(currentNode.leftChild);
- postOrder(currentNode.rightChild);
- System.out.print(currentNode.value + " ");
- }
- }
- public void traverse(int traverseType) {
- switch (traverseType) {
- case 1:
- preOrder(root);
- break;
- case 2:
- inOrder(root);
- break;
- case 3:
- postOrder(root);
- break;
- default:
- break;
- }
- }
- // 依据树节点的值删除树中的一个节点
- public boolean delete(int value) {
- // 遍历树过程中的当前节点
- Node current = root;
- // 要删除节点的父节点
- Node parent = root;
- // 记录树的节点为左孩子节点或右孩子节点
- boolean isLeftChild = true;
- while (current.value != value) {
- parent = current;
- // 要删除的节点在当前节点的左子树里
- if (value < current.value) {
- isLeftChild = true;
- current = current.leftChild;
- }
- // 要删除的节点在当前节点的右子树里
- else {
- isLeftChild = false;
- current = current.rightChild;
- }
- // 在树中没有找到要删除的节点
- if (current == null)
- return false;
- }
- // 要删除的节点为叶子节点
- if (current.leftChild == null && current.rightChild == null) {
- // 要删除的节点为根节点
- if (current == root)
- root = null;
- // 要删除的节点为左孩子节点
- else if (isLeftChild)
- parent.leftChild = null;
- // 要删除的节点为右孩子节点
- else
- parent.rightChild = null;
- }
- // 要删除的节点有左孩子节点,没有右孩子节点
- else if (current.rightChild == null) {
- // 要删除的节点为根节点