博客
关于我
java遍历二叉树
阅读量:202 次
发布时间:2019-02-28

本文共 3518 字,大约阅读时间需要 11 分钟。

问题分析

由于不论先序还是中序、后序遍历,在程序运行流程上没有本质区别,区别仅仅是访问语句的执行时间点。因此,只要有了先序的程序流程,改变一下访问语句代码位置,就可以实现前三种遍历方式。

先序遍历(非递归)

先序遍历是从树的根节点开始,依次访问左节点和右节点。非递归实现使用栈来模拟调用栈,确保每个节点只被访问一次。

public void visitFirst_N(Node tree) {    if (tree != null) {        Stack
stack = new Stack<>(); stack.push(tree); Node current = tree; while (current != null) { System.out.print(current.value + " "); current = current.left; if (current != null) { stack.push(current); } else { while (!stack.isEmpty()) { Node node = stack.pop(); current = node.right; if (current != null) { stack.push(current); break; } } } } }}

中序遍历(非递归)

中序遍历是从树的根节点开始,先访问左节点,后访问右节点。非递归实现仍然使用栈,但处理方式有所不同。

public void midTest(Node tree) {    if (tree != null) {        Stack
stack = new Stack<>(); stack.push(tree); Node current = tree; while (current != null) { current = current.left; if (current != null) { stack.push(current); } else { while (!stack.isEmpty()) { Node node = stack.pop(); System.out.print(node.value + " "); current = node.right; if (current != null) { stack.push(current); break; } } } } }}

后序遍历(非递归)

后序遍历是从树的根节点开始,先访问右节点,再访问左节点。由于栈的先进后出特性,需要额外处理栈中的节点,确保左节点在栈底部。

public void LastTest(Node tree) {    if (tree != null) {        Stack
stack = new Stack<>(); stack.push(tree); Node current = tree; while (current != null) { current = current.left; if (current != null) { stack.push(current); } else { while (!stack.isEmpty()) { Node node = stack.peek(); current = node.right; if (current == null) { Node x = stack.pop(); System.out.print(x.value + " "); Node y = stack.pop(); if (y.left == x) { stack.push(y); current = y.right; } else { Node k = stack.peek(); System.out.print(y.value + " "); if (k.right == y) { while (!stack.isEmpty()) { System.out.print(stack.pop().value + " "); } return; } current = k.right; } } if (current != null) { stack.push(current); break; } } } } }}

层次遍历(非递归)

层次遍历是按层访问树节点。使用队列来实现,先处理队列中的节点,输出其值,然后将左孩子和右孩子入队。

private void visitLevel(Node x) {    Queue
queue = new Queue<>(); while (x != null) { System.out.print(x.value + " "); if (x.left != null) { queue.enqueue(x.left); } if (x.right != null) { queue.push(x.right); } x = queue.deQueue(); }}

通过上述实现,可以清晰地看到不同遍历方式在非递归情况下的实现差异。

转载地址:http://mpvi.baihongyu.com/

你可能感兴趣的文章
NuGet学习笔记001---了解使用NuGet给net快速获取引用
查看>>
nullnullHuge Pages
查看>>
NullPointerException Cannot invoke setSkipOutputConversion(boolean) because functionToInvoke is null
查看>>
null可以转换成任意非基本类型(int/short/long/float/boolean/byte/double/char以外)
查看>>
Numix Core 开源项目教程
查看>>
numpy
查看>>
NumPy 或 Pandas:将数组类型保持为整数,同时具有 NaN 值
查看>>
numpy 或 scipy 有哪些可能的计算可以返回 NaN?
查看>>
numpy 数组 dtype 在 Windows 10 64 位机器中默认为 int32
查看>>
numpy 数组与矩阵的乘法理解
查看>>
NumPy 数组拼接方法-ChatGPT4o作答
查看>>
numpy 用法
查看>>
Numpy 科学计算库详解
查看>>
Numpy.fft.fft和numpy.fft.fftfreq有什么不同
查看>>
Numpy.ndarray对象不可调用
查看>>
Numpy:按多个条件过滤行?
查看>>
Numpy:条件总和
查看>>
numpy、cv2等操作图片基本操作
查看>>
NumPy中的精度:比较数字时的问题
查看>>
numpy判断对应位置是否相等,all、any的使用
查看>>