import java.util.Stack;
/**
* 二叉树的中序遍历
*/
public class InOrder {
/**
* 二叉树的递归中序遍历
* @param binaryTree 二叉树
*/
public static void inOrder(BinaryTree binaryTree){
if(binaryTree != null){
//先遍历左节点
inOrder(binaryTree.left);
//再遍历中间节点
System.out.println(binaryTree.value);
//再遍历右节点
inOrder(binaryTree.right);
}
}
/**
* 非递归中序遍历
* @param binaryTree 二叉树
*/
public static void inOrder02(BinaryTree binaryTree){
BinaryTree node = binaryTree;
Stack<BinaryTree> stack = new Stack<>();
//终止条件
while(!stack.isEmpty() || node != null){
//循环的把左节点加入到栈中,直到二叉树的左节点为空
while(node != null){
stack.push(node);
//当前节点等于它的左节点
node = node.left;
}
//栈不为空的情况下再遍历
if(!stack.isEmpty()){
node = stack.pop();
System.out.println(node.value);
//右节点
node = node.right;
}
}
}
/**
* 非递归中序遍历
* @param binaryTree 二叉树
*/
public static void inOrder03(BinaryTree binaryTree){
BinaryTree node = binaryTree;
Stack<BinaryTree> stack = new Stack<>();
if(node == null){
return;
}
//终止条件
while(!stack.isEmpty() || node != null){
if(node != null){
stack.push(node);
node = node.left;
}
//栈不为空的情况下再遍历
else{
node = stack.pop();
System.out.println(node.value);
//右节点
node = node.right;
}
}
}
/**
* 测试结果
* @param args
*/
public static void main(String[] args){
//新建二叉树
BinaryTree root = new BinaryTree(1);
BinaryTree left = new BinaryTree(2);
BinaryTree right = new BinaryTree(3);
BinaryTree left02 = new BinaryTree(4);
BinaryTree right02 = new BinaryTree(5);
BinaryTree right03 = new BinaryTree(6);
left.right = right02;
left.left = left02;
root.left = left;
root.right = right;
right02.left = right03;
//中序遍历二叉树递归方式
inOrder(root);
System.out.println("-----------------");
inOrder02(root);
}
/*测试结果
*
* 426513
* -----------------
* 426513
*/
}
//二叉树的类
class BinaryTree{
int value;
BinaryTree left;
BinaryTree right;
public BinaryTree(int value){
this.value = value;
}
}