二叉树层级输出java,Java 非递归实现 二叉树的前中后遍历以及层级遍历

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;

}

}

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值