1.非递归遍历二叉树
非递归实现需要手动控制压栈的过程,目的既要保证每个节点都访问到且能有效控制程序结束
//先序遍历 先push right再push left,目的是先处理left节点 弹栈就打印
public static void prefix(Node node) {
System.out.print("pre-order: ");
Stack<Node> stack = new Stack<>();
stack.push(node);
while (!stack.empty()) {
node = stack.pop();
System.out.print(node.val + " ");
if (node.right != null) {
stack.push(node.right);
}
if (node.left != null) {
stack.push(node.left);
}
}
System.out.println();
}
//中序遍历: 只要left不为null一直往左窜直到null,并将沿途经过的节点压入栈,
//然后弹出即打印,再往右窜,不为空就往左窜,压栈...
public static void infill(Node node) {
System.out.print("infill-order: ");
Stack<Node> stack = new Stack<>();
//先不急压入头节点
while (!stack.isEmpty() || node != null){
if(node != null){
stack.push(node);
node = node.left;
}else{
node = stack.pop();
System.out.print(node.val + " ");
node = node.right;
}
}
System.out.println();
}
//后续遍历打印顺序:左 右 头 -> 逆序看: 头 右 左,那么就需要先push左才能先pop右
public static void post(Node node) {
System.out.print("post-order: ");
Stack<Node> stack = new Stack<>();
Stack<Node> data = new Stack<>();
stack.push(node);
while (!stack.empty()) {
node = stack.pop();
data.push(node);
if (node.left != null) {
stack.push(node.left);
}
if (node.right != null) {
stack.push(node.right);
}
}
while (!data.empty()){
System.out.print(data.pop().val + " ");
}
System.out.println();
}
2.递归遍历二叉树
public static void pref(Node node){
if(node == null){
return;
}
System.out.print(node.val + "\t");
pref(node.left);
pref(node.right);
}
public static void infill(Node node){
if(node == null){
return;
}
infill(node.left);
System.out.print(node.val + "\t");
infill(node.right);
}
public static void post(Node node){
if(node == null){
return;
}
post(node.left);
post(node.right);
System.out.print(node.val + "\t");
}
左神算法学习