二叉树中序非递归遍历
1、定义类
class Tree{
int val;
Tree leftTree;
Tree rigtTree;
}
2、中序非递归函数
public static void InOrderNoRescurison(Tree root){
if(root == null){
return;
}
//定义一个栈
Stack<Tree> stack = new Stack<testApp.Tree>();
Tree pTree = root;//定义一个指向root的节点
//中序非递归遍历口诀:
//入栈向左一直走
//出栈访问右之树
//这是循环控制条件,注意这里的pTree需要判断为空才是结束循环,只通过栈判断循环结束是错误的
while(pTree != null || !stack.isEmpty()){
if(pTree != null){
//入栈向左一直走
stack.push(root);
pTree = pTree.leftTree;
}else{
//出栈访问右之树
Tree tempTreeNodeTree = stack.pop();
System.out.println(tempTreeNodeTree.val);
pTree = pTree.rigtTree;
}
}
}