前序遍历:先输出父节点、再输出左子树、再输出右子树。
中序遍历:先输出左子树、再输出父节点、再输出右子树。
后序遍历:先输出左子树、再输出右子树、再输出父节点。
广度优先遍历层遍历:从上到下,从左到右,依次输出节点的值
新建TreeNode节点
public class TreeNode {
public TreeNode lc;//左子树
public TreeNode rc;//右子树
public Integer value;//插入的值
public TreeNode(Integer value) {
this.value = value;
}
}
深度优先遍历
前序遍历
public void xx(TreeNode node) {
if (node != null) {
System.out.print(node.value + " ");
xx(node.lc);
xx(node.rc);
}
}
中序遍历
public void zx(TreeNode node) {
if (node != null) {
zx(node.lc);
System.out.print(node.value + " ");
zx(node.rc);
}
}
后序遍历
public void hx(TreeNode node) {
if (node != null) {
hx(node.lc);
hx(node.rc);
System.out.print(node.value + " ");
}
}
广度优先遍历
层序遍历
这里需要利用队列,我们直接用JDK自带的方法
add()向队列加值
pop()输出队列第一个数
// 层遍历(利用队列)
// add()向队列加值 pop()输出队列第一个数
public void c() {
linkedList queue = new linkedList<>();
queue.add(root);
while (!queue.isEmpty()) {
TreeNode treeNode = queue.pop();
System.out.println(treeNode.value);
if (treeNode.lc != null) {
queue.add(treeNode.lc);
}
if (treeNode.rc != null) {
queue.add(treeNode.rc);
}
}
}
实现类(记得程序加上二叉树的创建,我的主页有二叉树创建)
public class Test {
public static void main(String[] args) {
BinaryTree xx=new BinaryTree();
xx.insert(5);
xx.insert(4);
xx.insert(7);
xx.insert(2);
xx.insert(0);
xx.insert(9);
xx.insert(10);
System.out.print("先序遍历:");
xx.xx(xx.root);
System.out.println("");
System.out.print("中序遍历:");
xx.zx(xx.root);
System.out.println("");
System.out.print("后序遍历:");
xx.hx(xx.root);
System.out.println("");
System.out.print("层遍历:");
xx.c();
}
}
结果



