二叉树的遍历方式
使用Java实现了二叉树的前序、中序、后序遍历的递归版本和非递归版本,以及层序遍历。
代码实现
public class Traversal {
// 前序遍历递归
public static void preOrder(Node root) {
if (root == null) {
return;
}
System.out.print(root.value + " ");
preOrder(root.left);
preOrder(root.right);
}
// 中序遍历递归
public static void inOrder(Node root) {
if (root == null) {
return;
}
inOrder(root.left);
System.out.print(root.value + " ");
inOrder(root.right);
}
// 后序遍历递归
public static void posOrder(Node root) {
if (root == null) {
return;
}
posOrder(root.left);
posOrder(root.right);
System.out.print(root.value + " ");
}
// 前序遍历非递归(先压右后压左)
public static void preOrderUnRecur(Node root) {
if (root != null) {
Stack<Node> stack = new Stack<>();
stack.push(root);
while (!stack.isEmpty()) {
Node curNode = stack.pop();
System.out.print(curNode.value + " ");
if (curNode.right != null) {
stack.push(curNode.right);
}
if (curNode.left != null){
stack.push(curNode.left);
}
}
}
System.out.println();
}
// 中序遍历非递归
public static void inOrderUnRecur(Node root) {
// 将树的所有左边界压入栈中,当不能再进行压栈时,弹出并打印该元素,
// 判断该元素是否有右子树,如果有则继续将右子树的所有左边界压栈
if (root != null) {
Stack<Node> stack = new Stack<>();
while (!stack.isEmpty() || root != null) {
if (root != null) {
stack.push(root);
root = root.left;
} else {
root = stack.pop();
System.out.print(root.value + " ");
root = root.right;
}
}
System.out.println();
}
}
// 后序遍历非递归(先压左后压右---->[中,右,左],使用另一个栈实现逆序---->[左,右,中])
public static void posOrderUnRecur(Node root) {
if (root != null) {
Stack<Node> stack1 = new Stack<>();
Stack<Node> stack2 = new Stack<>();
stack1.push(root);
while (!stack1.isEmpty()) {
Node curNode = stack1.pop();
stack2.push(curNode);
if (curNode.left != null) {
stack1.push(curNode.left);
}
if (curNode.right != null) {
stack1.push(curNode.right);
}
}
while (!stack2.isEmpty()) {
System.out.print(stack2.pop().value + " ");
}
System.out.println();
}
}
// 层序遍历(使用队列)
public static void levelOrder(Node root) {
if (root != null) {
Queue<Node> queue = new LinkedList<>();
queue.offer(root);
while(!queue.isEmpty()) {
Node curNode = queue.poll();
System.out.print(curNode.value + " ");
if (curNode.left != null) {
queue.offer(curNode.left);
}
if (curNode.right != null) {
queue.offer(curNode.right);
}
}
}
}
public static void main(String[] args) {
// 测试
Node root = new Node(1);
root.left = new Node(2);
root.right = new Node(3);
root.left.left = new Node(4);
root.left.right = new Node(5);
root.right.left = new Node(6);
root.right.right = new Node(7);
System.out.println("前序遍历");
preOrder(root);
System.out.println();
preOrderUnRecur(root);
System.out.println("中序遍历");
inOrder(root);
System.out.println();
inOrderUnRecur(root);
System.out.println("后序遍历");
posOrder(root);
System.out.println();
posOrderUnRecur(root);
System.out.println("层序遍历");
levelOrder(root);
}
}
本文详细介绍了如何使用Java实现二叉树的前序、中序、后序遍历的递归和非递归版本,以及层序遍历。通过具体的代码示例,展示了每种遍历方法的实现细节,包括递归版本的简洁性和非递归版本的逻辑处理。这些方法对于理解和操作二叉树结构非常有帮助。
991

被折叠的 条评论
为什么被折叠?



