import java.util.LinkedList;
import java.util.Stack;
//构造我自己的树
public class MyTree {
public static void main(String[] args) {
Node<Integer> root = new Node<Integer>(1);
root.setLeft(new Node<Integer>(2));
root.setRight(new Node<Integer>(3));
root.left.setLeft(new Node<Integer>(4));
root.left.setRight(new Node<Integer>(5));
root.right.setLeft(new Node<Integer>(6));
root.right.setRight(new Node<Integer>(7));
System.out.print("前序遍历:");
System.out.println(root.toStringPreorder());
System.out.print("中序遍历:");
System.out.println(root.toStringInorder());
System.out.print("后序遍历:");
System.out.println(root.toStringPostorder());
System.out.print("广度优先:");
System.out.println(root.toStringLevelOrder());
}
}
// 对于一个结点,可以设定结点中的元素,得到其中的元素,设定其左边的元素,
// 设定其右边的元素,得到其左边的元素,得到其右边的元素
class Node<E> {
E item;
Node(E item) {
this.item = item;
}
public void setItem(E item) {
this.item = item;
}
public E getItem() {
return this.item;
}
Node<E> left;
public void setLeft(Node<E> node) {
this.left = node;
}
public Node<E> getLeft() {
return this.left;
}
Node<E> right;
public void setRight(Node<E> node) {
this.right = node;
}
public Node<E> getRight() {
return this.right;
}
public boolean isLeaf() {
return this.left == null && this.right == null;
}
// 前序遍历(pre-order),根-左-右(递归版本)
// public String toStringPreorder() {
// String res = "";
// res += item;
// if(this.left != null) {
// res += this.left.toStringPreorder();
// }
//
// if(this.right != null) {
// res += this.right.toStringPreorder();
// }
// return res;
// }
// 前序遍历(pre-order),根-左-右(迭代版本)
public String toStringPreorder() {
String res = "";
Stack<Node<E>> stack = new Stack<Node<E>>();
stack.push(this);
while (!stack.empty()) {
Node<E> node = stack.pop();
res += node.item;
if (node.right != null) {
stack.push(node.right);
}
if (node.left != null) {
stack.push(node.left);
}
}
return res;
}
// 中序遍历(in-order),左-根-右(递归版本)
public String toStringInorder() {
String res = "";
if (this.left != null) {
res += this.left.toStringInorder();
}
res += item;
if (this.right != null) {
res += this.right.toStringInorder();
}
return res;
}
// 后序遍历(post-order),左-右-根
public String toStringPostorder() {
String res = "";
if (this.left != null) {
res += this.left.toStringPostorder();
}
if (this.right != null) {
res += this.right.toStringPostorder();
}
res += item;
return res;
}
// 层序遍历(level),又称广度优先搜索
public String toStringLevelOrder() {
String res = "";
MyQueue<Node<E>> queue = new MyQueue<Node<E>>();
queue.add(this);
while (!queue.isEmpty()) {
Node<E> node = queue.remove();
res += node.item;
if (node.left != null) {
queue.add(node.left);
}
if (node.right != null) {
queue.add(node.right);
}
}
return res;
}
}
class MyQueue<E> {
LinkedList<E> l = new LinkedList<E>();
void add(E item) {
l.add(item);
}
E remove() {
return l.removeFirst();
}
boolean isEmpty() {
return l.isEmpty();
}
}