使用栈配合,才能实现树的非递归后续遍历
package com.bupt;
import java.util.Stack;
class Tree{
int data;
Tree lchild = null;
Tree rchild = null;
}
//class Stack{
// Tree[] data = new Tree[50];
// int top = -1;
//}
public class Solution2 {
public static void find(Tree t){
if(t!=null){
System.out.println(t.data);
find(t.lchild);
find(t.rchild);
}
}
public static void findPost(Tree t){
Tree p = new Tree();
Tree r = new Tree();
Stack<Tree> s = new Stack<Tree>();
p = t;
while(p!=null||!s.isEmpty()){
if(p!=null){
s.push(p);
p = p.lchild;
}else{
p = s.peek();
if(p.rchild!=null && p.rchild!=r){
p = p.rchild;
s.push(p);
p = p.lchild;
}else{
p = s.pop();
System.out.println(p.data);
r = p;
p = null;
}
}
}
}
public static void main(String[] args){
Tree t = new Tree();
t.data = 2;
t.lchild = new Tree();
t.lchild.data = 1;
t.lchild.lchild = new Tree();
t.lchild.rchild = new Tree();
t.lchild.lchild.data = 4;
t.lchild.rchild.data = 5;
t.rchild = new Tree();
t.rchild.data = 3;
findPost(t);
}
}