class MyBinaryTree{
BinaryNoderoot;publicMyBinaryTree() {
root= new BinaryNode<>();
}/*** 堆栈进行先序遍历
*
*@paramts*/
public voidpreorderTraversal(T... ts) {
Stack> binaryStack = new Stack<>();
BinaryNode temp =root;while (!binaryStack.isEmpty() || temp != null) {if (temp != null) {//处理
System.out.println(temp.data);//先序
if (temp != null) {
binaryStack.push(temp);
}
temp=temp.left;
}else{
temp=binaryStack.pop();
temp= temp.right != null ? temp.right : null;
}
}
}/*** 堆栈中序遍历
*
*@paramts*/
public voidinorderTraversal(T... ts) {
Stack> binaryStack = new Stack<>();
BinaryNode temp =root;while (!binaryStack.isEmpty() || temp != null) {if (temp != null) {
binaryStack.push(temp);
temp=temp.left;
}else{
temp=binaryStack.pop();//处理
System.out.println(temp.data);
temp= temp.right != null ? temp.right : null;
}
}
}/*** 堆栈后序遍历
*
*@paramts*/
public voidpostorderTraversal(T... ts) {
Stack> binaryStack = new Stack<>();
BinaryNode temp =root;
BinaryNode node = null;while (!binaryStack.isEmpty() || temp != null) {if (temp != null) {
binaryStack.push(temp);
temp=temp.left;
}else{
temp=binaryStack.pop();if (temp.right == null || temp.right ==node) {//处理
System.out.println(temp.data);
node=temp;
temp= null;
}else{
binaryStack.push(temp);
temp=temp.right;
binaryStack.push(temp);
temp=temp.left;
}
}
}
}/*** 层级遍历*/
public voidlevelTraversal() {
BinaryNode temp =root;
Queue> queue = new LinkedList<>();
queue.add(temp);while(!queue.isEmpty()) {
temp=queue.poll();
// 处理
System.out.println(temp.data);if(temp.left!=null) {
queue.add(temp.left);
}if(temp.right!=null) {
queue.add(temp.right);
}
}
}
}class BinaryNode{
BinaryNodeleft;
T data;
BinaryNoderight;publicBinaryNode() {
}public BinaryNode(BinaryNode left, T data, BinaryNoderight) {this.left =left;this.data =data;this.right =right;
}
}