二叉树先序中序后序遍历的非递归实现
Posted 不做油腻的中年大叔
tags:
篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了二叉树先序中序后序遍历的非递归实现相关的知识,希望对你有一定的参考价值。
一、题目
题目如标题,我们先回顾一下二叉树遍历的递归版本
public static class Node{
public int value;
public Node left;
public Node right;
public Node(int data){
this.value = data;
}
}
public static void preOrderRecur(Node head){
if(head == null){
return ;
}
System.out.print(head.value + " ");
preOrderRecur(head.left);
preOrderRecur(head.right);
}
public static void inOrderRecur(Node head){
if(head == null){
return ;
}
inOrderRecur(head.left);
System.out.print(head.value + " ");
inOrderRecur(head.right);
}
public static void posOrderRecur(Node head){
if(head == null){
return;
}
posOrderRecur(head.left);
posOrderRecur(head.right);
System.out.print(head.value + " ");
}
二、分析非递归实现
先序
一个栈,先放入头节点
如果栈非空,弹出一个节点,打印,并先放右再放左
直到栈空
中序
一个栈,把从中间到左边的所有节点(一路左)放入栈中
弹出一个节点,打印,并将其右子树的一路左放入栈中
直到栈为空
后序
先序遍历的顺序是中左右,那么只需要改变先序压栈的顺序,即可实现中右左的顺序,再设置一个help栈,将本该直接弹出打印的节点压入help栈,最后再从help栈弹出,即为后序遍历的顺序,左右中。
三、非递归实现
public static void preOrderUnRecur(Node head){
System.out.print("pre-order: ");
if(head != null){
Stack<Node> stack = new Stack<>();
stack.push(head);
while(!stack.isEmpty()){
head = stack.pop();
System.out.print(head.value + " ");
if(head.right != null){
stack.push(head.right);
}
if(head.left != null){
stack.push(head.left);
}
}
}
System.out.println();
}
public static void inOrderUnRecur(Node head){
System.out.print("in-order: ");
if(head != null){
Stack<Node> stack = new Stack<>();
while(head != null || !stack.isEmpty()){
if(head != null){
stack.push(head);
head = head.left;
}
else{
head = stack.pop();
System.out.print(head.value + " ");
head = head.right;
}
}
}
System.out.println();
}
public static void posOrderUnRecur(Node head){
System.out.print("pos-order: ");
if(head != null){
Stack<Node> stack = new Stack<>();
Stack<Node> help = new Stack<>();
stack.push(head);
while(!stack.isEmpty()){
head = stack.pop();
help.push(head);
if(head.left != null){
stack.push(head.left);
}
if(head.right != null){
stack.push(head.right);
}
}
while(!help.isEmpty()){
System.out.print(help.pop().value + " ");
}
}
System.out.println();
}
以上是关于二叉树先序中序后序遍历的非递归实现的主要内容,如果未能解决你的问题,请参考以下文章