1.递归方式实现二叉树先中后序遍历
public class Code01_DgModel {
//定义节点的类型
public class Node{
public int value;
public Node right;
public Node left;
public Node(int val){
this.value = val;
}
}
//先序遍历 头左右
public void preOrderRecur(Node head){
if(head==null){
return;
}
System.out.println(head.value+ " ");
preOrderRecur(head.left);
preOrderRecur(head.right);
}
//中序遍历 左头右
public void inOrderRecur(Node head){
if(head==null){
return;
}
inOrderRecur(head.left);
System.out.println(head.value + " ");
inOrderRecur(head.right);
}
//后续遍历 左右头
public void inPosRecur(Node head){
if(head==null){
return;
}
inPosRecur(head.left);
inPosRecur(head.right);
System.out.println(head.value+ " ");
}
}
在代码上展示打印递归版本的三种顺序的方式就是打印时机的不同
2.非递归方式实现二叉树的先中后序遍历
public class Code01_NoDgModel {
public class Node {
public int value;
public Node right;
public Node left;
public Node(int val) {
this.value = val;
}
}
// 前序 中左右
public void preOrderUnRecur(Node head) {
if (head != null) {
Stack<Node> stack = new Stack<Node>();
//栈压节点
stack.add(head);
//这段代码的逻辑就是栈不空,弹出一个节点 弹出则压子节点的栈
//遵循先有右压右后有左压左的原则 栈先进后出的作用下达到头左右的效果
while (!stack.isEmpty()) {
head = stack.pop();
System.out.println(