二叉树有前序遍历,中序遍历,后序遍历。大部分情况,我们都是用递归来写这些遍历,代码简洁明了。
如果能用非递归来写这些遍历,那么会对这些遍历理解得更深刻。
前序遍历递归写法:
private void displayPreOrder(Node root) {
if (root != null) {
System.out.print(" " + root.data);
displayPreOrder(root.left);
displayPreOrder(root.right);
}
}
前序遍历得非递归写法要根据递归运行步骤用栈来实现前序遍历。前序遍历就是在有孩子得情况下先遍历自己再管孩子。每次遍历完自己就从栈中pop出来,再把孩子push到栈里。如此循环就能实现前序遍历。
private void displayPreOrderNoRecursion(Node root) {
Stack<Node> s = new Stack<Node>();
Node cur;
if(root != null)
s.push(root);
while(!s.isEmpty()) {
cur = s.pop();
System.out.print(" " + cur.data);
if(cur.right != null) {
s.push(cur.right);
}
if(cur.left != null) {
s.push(cur.left);
}
}
}
中序遍历递归写法:
private void displayInOrder(Node root) {
if (root != null) {
displayInOrder(root.left);
System.out.print(" " + root.data);
displayInOrder(root.right);
}
}
中序遍历非递归写法根据递归写法步骤用栈来实现中序遍历,因为我们这里是先遍历左孩子再遍历自己最后遍历右孩子,所以我们先把二叉树所有的左孩子从上到下push到栈中,然后每次遍历从栈中pop出的节点并且检测是否有右孩子,如果有右孩子就把右孩子push到栈中,然后继续遍历该节点的所有的左孩子从上到下push到栈中,如此循环就能实现中序遍历。
private void displayInOrderNonRecursion(Node root) {
Stack<Node> s = new Stack<Node>();
Node current = root;
while(current != null) {
s.push(current);
current = current.left;
}
while(!s.isEmpty()) {
current = s.pop();
System.out.print(" " + current.data);
if(current.right != null) {
current = current.right;
s.push(current);
while(current.left != null) {
current = current.left;
s.push(current);
}
}
}
}
接下来是后序遍历,稍有些复杂。
后序遍历递归写法:
private void displayPostOrder(Node root) {
if (root != null) {
displayPostOrder(root.left);
displayPostOrder(root.right);
System.out.print(" " + root.data);
}
}
后序遍历的非递归写法就是按照递归写法的步骤实现的。后序遍历顾名思义就是先遍历左孩子右孩子最后再遍历自己。先将根结点push栈中,接下来在检测栈是否为空的循环条件下,检测该检查栈顶节点如果没有孩子或者有孩子且孩子已经被遍历的情况就将该节点pop出来遍历,然后根据该节点查看是否有左孩子或者右孩子,如果有,就按照先查看右孩子再查看左孩子的顺序将孩子push栈中。因为我们是先遍历左孩子再遍历右孩子所以push入栈的顺序应该是先push右孩子再push左孩子,这样再pop的时候就是先取左孩子再取右孩子。这样循环就能实现后序遍历。
private void displayPostOrderNonRecursion(Node root) {
Stack<Node> s = new Stack<Node>();
if(root != null)
s.push(root);
Node current = null;
Node pre = null;
while(!s.isEmpty()) {
current = s.peek();
if((current.left == null && current.right == null) ||
(pre != null && (pre == current.left || pre == current.right))) {
s.pop();
System.out.print(" " + current.data);
pre = current;
} else {
if(current.right != null) {
s.push(current.right);
}
if(current.left != null) {
s.push(current.left);
}
}
}
}