java 树的遍历_java 递归实现树的遍历

这篇博客详细介绍了如何使用Java实现二叉树的顺序表示,并提供了前序、中序、后序遍历以及按层遍历的算法。通过一个静态数组初始化二叉树,并使用递归函数进行构建。此外,还包含了判断二叉树是否为空及获取遍历字符串的方法。
摘要由CSDN通过智能技术生成

public class BitTree {

public static Node2 root;

public static String asString;

//事先存入的数组,符号#表示二叉树结束。

public static final char[] treeLine =

{'a','b','c','d','e','f','g',' ',' ','j',' ',' ','i','#'};

//用于标志二叉树节点在数组中的存储位置,以便在创建二叉树时能够找到节点对应的数据。

static int index;

//构造函数

public BitTree() {

System.out.print("测试二叉树的顺序表示为:");

System.out.println(treeLine);

this.index = 0;

root = this.setup(root);

}

//创建二叉树的递归程序

private Node2 setup(Node2 current) {

if (index >= treeLine.length) return current;

if (treeLine[index] == '#') return current;

if (treeLine[index] == ' ') return current;

current = new Node2(treeLine[index]);

index = index * 2 + 1;

current.left = setup(current.left);

index ++;

current.right = setup(current.right);

index = index / 2 - 1;

return current;

}

//二叉树是否为空。

public boolean isEmpty() {

if (root == null) return true;

return false;

}

//返回遍历二叉树所得到的字符串。

public String toString(int type) {

if (type == 0) {

asString = "前序遍历:\t";

this.front(root);

}

if (type == 1) {

asString = "中序遍历:\t";

this.middle(root);

}

if (type == 2) {

asString = "后序遍历:\t";

this.rear(root);

}

if (type == 3) {

asString = "按层遍历:\t";

this.level(root);

}

return asString;

}

//前序遍历二叉树的循环算法,每到一个结点先输出,再压栈,然后访问它的左子树,

//出栈,访问其右子树,然后该次循环结束。

private void front(Node2 current) {

StackL stack = new StackL((Object)current);

do {

if (current == null) {

current = (Node2)stack.pop();

current = current.right;

} else {

asString += current.ch;

current = current.left;

}

if (!(current == null)) stack.push((Object)current);

} while (!(stack.isEmpty()));

}

//中序遍历二叉树

private void middle(Node2 current) {

if (current == null) return;

middle(current.left);

asString += current.ch;

middle(current.right);

}

//后序遍历二叉树的递归算法

private void rear(Node2 current) {

if (current == null) return;

rear(current.left);

rear(current.right);

asString += current.ch;

}

}

public class Node2 {

char ch;

Node2 left;

Node2 right;

//构造函数

public Node2(char c) {

this.ch = c;

this.left = null;

this.right = null;

}

//设置节点的值

public void setChar(char c) {

this.ch = c;

}

//返回节点的值

public char getChar() {

return ch;

}

//设置节点的左孩子

public void setLeft(Node2 left) {

this.left = left;

}

//设置节点的右孩子

public void setRight (Node2 right) {

this.right = right;

}

//如果是叶节点返回true

public boolean isLeaf() {

if ((this.left == null) && (this.right == null)) return

true;

return false;

}

}

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值