题目描述
实现二叉树的先序、中序、后序遍历,包括递归方式和非递归方式
实现
递归方式
public static class Node {
int val;
Node left;
Node right;
public Node(int data) {
this.val = data;
}
}
// 前序递归
public static void preTraversal(Node head) {
if (head == null) return;
System.out.print(head.val + " ");
preTraversal(head.left);
preTraversal(head.right);
}
// 中序递归
public static void inTraversal(Node head) {
if (head == null) return;
inTraversal(head.left);
System.out.print(head.val + " ");
inTraversal(head.right);
}
// 后序递归
public static void posTraversal(Node head) {
if (head == null) return;
posTraversal(head.left);
posTraversal(head.right);
System.out.print(head.val + " ");
}
非递归方式
前序
使用栈结构来实现,注意压栈先压右孩子,这样出栈顺序后出右孩子。
// 前序非递归
public static void preTravelsal1(Node head) {
if (head == null) return;
Stack<Node> stack = new Stack<>();
stack.push(head);
while (!stack.isEmpty()) {
head = stack.pop();
System.out.print(head.val + " ");
if (head.right != null) stack.push(head.right);
if (head.left != null) stack.push(head.left);
}
}
中序
利用栈结构来实现。
- 当前节点不为空,压入栈,当前节点为左孩子
- 当前节点为空,从栈中拿一个,当前节点为右孩子
// 中序非递归
public static void inTravelsal1(Node head) {
if (head == null) return;
Stack<Node> stack = new Stack<>();
while (!stack.isEmpty() || head != null) {
if (head != null) {
stack.push(head);
head = head.left;
} else {
head = stack.pop();
System.out.print(head.val + " ");
head = head.right;
}
}
}
后序
前序遍历是根左右,后序遍历是左右根。
那么在非递归版本中很容易将根左右顺序,换成根右左顺序。然后在每次前序遍历输出打印的地方,把当前节点存入到第二个栈中:根右左。
最后将第二个栈中的数据一个个弹出来的时候,就是左右根的顺序
// 后序非递归
public static void posTravelsal(Node head){
if(head == null) return;
Stack<Node> s1 = new Stack<>();
Stack<Node> s2 = new Stack<>();
s1.push(head);
while(!s1.isEmpty()){
head = s1.pop();
s2.push(head);
if(head.left != null) s1.push(head.left);
if(head.right != null) s2.push(head.right);
}
while(!s2.isEmpty()){
System.out.print(s2.pop().val + " ");
}
}