非递归实现二叉树遍历

时间:2021-04-08 10:25:28

借助栈来实现的非递归方式:

先序遍历和中序遍历都比较简单,就不解释了。简单解释一下后序遍历,上述二叉树的后序遍历结果是:214538796。将后序遍历结果逆序得到:697835412。即逆后序遍历结果为:697835412。通过观察逆后序遍历结果,可发现,逆后序遍历结果可以通过将前序遍历的遍历顺序的第二步和第三步互换一下即可。即:先遍历根节点,然后遍历右孩子,最后遍历左孩子。

//===============采用非递归方式========================
public void theFirstTraversal_Stack(Node root) { //先序遍历
Stack<Node> stack = new Stack<Node>();
Node node = root;
while (node != null || stack.size() > 0) { //将所有左孩子压栈
if (node != null) { //压栈之前先访问
printNode(node);
stack.push(node);
node = node.getLeftNode();
} else {
node = stack.pop();
node = node.getRightNode();
}
}
}
  public void theInOrderTraversal_Stack(Node root) {  //中序遍历
Stack<Node> stack = new Stack<Node>();
Node node = root;
while (node != null || stack.size() > 0) {
if (node != null) {
stack.push(node); //直接压栈
node = node.getLeftNode();
} else {
node = stack.pop(); //出栈并访问
printNode(node);
node = node.getRightNode();
}
}
}
  public void thePostOrderTraversal_Stack(Node root) {   //后序遍历
Stack<Node> stack = new Stack<Node>();
Stack<Node> output = new Stack<Node>();//构造一个中间栈来存储逆后序遍历的结果
Node node = root;
while (node != null || stack.size() > 0) {
if (node != null) {
output.push(node);
stack.push(node);
node = node.getRightNode();
} else {
node = stack.pop();
node = node.getLeftNode();

}
}
while (output.size() > 0) {
printNode(output.pop());
}
}