二叉树基础遍历——非递归方法
内部结点类即主函数中方法调用
public static void main(String[] args) {
TreeNode g = new TreeNode(null, null, 2);
TreeNode e = new TreeNode(g, null, 4);
TreeNode d = new TreeNode(null, null, 5);
TreeNode b = new TreeNode(d, e, 7);
TreeNode f = new TreeNode(null, null, 3);
TreeNode c = new TreeNode(null, f, 6);
TreeNode a = new TreeNode(c, null, 8);
TreeNode root = new TreeNode(a, b, 9);
preBianli(root);//9 8 6 3 7 5 4 2
System.out.println();
midBianli(root);//6 3 8 9 5 7 2 4
System.out.println();
lastBianli(root);//
}
private static class TreeNode{
int val;
TreeNode left;
TreeNode right;
public TreeNode(int val) {
this.val = val;
}
public TreeNode(TreeNode left,TreeNode right,int val) {
this.left = left;
this.right = right;
this.val = val;
}
}
**
- 先序遍历
**
//非递归前序遍历
public static void preBianli(TreeNode node) {
/*
* 思维:先根,再左子树,再右子树
*/
TreeNode root = node;
Stack<TreeNode> stack = new Stack<>();
while(node != null || !stack.isEmpty()) {//树不为空或栈中还有元素,就继续遍历
while(node != null) {//直到左子树再没有左子节点
//打印当前结点(根)
System.out.print(node.val + " ");
//将当前结点入栈
stack.push(node);
//遍历左子树
node = node.left;
}
if (!stack.isEmpty()) {//栈不为空时出栈
node = stack.pop();
node = node.right;//遍历当前结点的右子节点
}
}
}
**
2.中序遍历
**
//非递归方法实现中序遍历
/*
* 思维:先左子树,再根,再右子树
*/
public static void midBianli(TreeNode node) {
Stack<TreeNode> stack = new Stack<>();
TreeNode root = node;
while(node != null || !stack.isEmpty()) {
while(node != null) {
//遍历左子树 进栈
stack.push(node);
node = node.left;
}
if (!stack.isEmpty()) {
node = stack.pop();//出栈 打印当前结点
System.out.print(node.val +" ");
//遍历当前结点的右子树
node = node.right;
}
}
}
**
- 后序遍历
**
//非递归方法实现后续遍历
public static void lastBianli(TreeNode node) {
/*
* 思维:先左子结点,再右子结点,最后根结点。
* 将根结点入栈,依次遍历左子结点入栈,直到左子节点遍历完,开始出栈;
出栈时,判断当前结点的右子结点是否为空,
若为空或是当前结点的右子结点已经遍历了,则打印当前结点,将当前结点赋值给临时的辅助结点(用来判断当前结点的右子节点是否已经遍历了)
若不为空则再将该结点入栈,并遍历右子节点 入栈(继续遍历右子节点的所有左子节点,入栈)
*/
Stack<TreeNode> stack = new Stack<>();
TreeNode temp = null;
while(node != null || !stack.isEmpty()) {
while(node != null) {
stack.push(node);
node = node.left;//遍历左子树 入栈
}
while(!stack.isEmpty()) {
node = stack.pop();
if (node.right == null || node.right == temp) {
System.out.print(node.val+ " ");
temp = node;
}else {
//右子节点不为空且没有遍历
stack.push(node);
node = node.right;
while(node != null) {
stack.push(node);
node = node.left;
}
}
}
}
}