import java.util.Stack;
import java.util.Stack;
/**
* 定义二叉树
* */
class BinaryTreeNode {
int value;
BinaryTreeNode left;
BinaryTreeNode right;
public BinaryTreeNode() {
}
public BinaryTreeNode(int val) {
this.value = val;
}
}
public class Solution{
/** 非递归实现前序遍历 */
protected void nonRecursivePreorder(BinaryTreeNode root) {
Stack<BinaryTreeNode> stack = new Stack<BinaryTreeNode>();
if (root != null) {
stack.push(root);
while (!stack.empty()) {
root = stack.pop();
visit(root);
if (root.right != null)
stack.push(root.right);
if (root.left != null)
stack.push(root.left);
}
}
}
public void nonRecursiveInOrder(BinaryTreeNode root) {
Stack<BinaryTreeNode> stack = new Stack<BinaryTreeNode>();
BinaryTreeNode current;
current = root;
while ((current != null) || (!stack.empty())) {
if (current != null) {
stack.push(current);
current = current.left;
} else {
current = (BinaryTreeNode) stack.pop();
visit(current);
current = current.right;
}
}
}
/**
* 后序遍历递归定义:先左子树,后右子树,再根节点。
*后序遍历的难点在于:需要判断上次访问的节点是位于左子树,还是右子树。
*若是位于左子树,则需跳过根节点,先进入右子树,再回头访问根节点;
*若是位于右子树,则直接访问根节点。
*/
public void nonRecursivePostOrder(BinaryTreeNode root){
if(root==null)
return;
Stack<BinaryTreeNode> stack = new Stack<BinaryTreeNode>();
BinaryTreeNode curNode;
BinaryTreeNode lastVisitNode = null;
curNode = root;
while(curNode!=null){
stack.push(curNode);
curNode = curNode.left;
}
while(!stack.empty()){
curNode = stack.pop();
if(curNode.right!=null&&curNode.right!=lastVisitNode){
stack.push(curNode);
curNode = curNode.right;
while(curNode!=null){
stack.push(curNode);
curNode = curNode.left;
}
}else{
visit(curNode);
lastVisitNode = curNode;
}
}
}
/** 访问节点 */
public void visit(BinaryTreeNode node) {
System.out.print(node.value + " ");
}
public static void main(String[] args)
{
BinaryTreeNode root=new BinaryTreeNode(1);
BinaryTreeNode left1=new BinaryTreeNode(2);
BinaryTreeNode left2=new BinaryTreeNode(3);
BinaryTreeNode right1=new BinaryTreeNode(4);
BinaryTreeNode right2=new BinaryTreeNode(5);
root.left=left1;
left1.right=left2;
root.right=right1;
right1.right=right2;
Solution test = new Solution();
test.nonRecursivePreorder(root);
System.out.println();
test.nonRecursiveInOrder(root);
System.out.println();
test.nonRecursivePostOrder(root);
}
}