参考https://blog.csdn.net/qswdaw/article/details/124078136
public class Test1 {
public static void main(String[] args) {
Tree eTree = new Tree ("E", new Tree ("H"), new Tree ("I"));
Tree cTree = new Tree ("C", new Tree ("F"), new Tree ("G"));
Tree bTree = new Tree ("B", new Tree ("D"), eTree);
Tree root = new Tree ("A", bTree, cTree);
List<String> list = new ArrayList<>();
preOrder(list,root);
list.stream().forEach(e-> System.out.print(e+"\t"));
System.out.println();
list = new ArrayList<>();
inOrder(list,root);
list.stream().forEach(e-> System.out.print(e+"\t"));
System.out.println();
list = new ArrayList<>();
afterOrder(list,root);
list.stream().forEach(e-> System.out.print(e+"\t"));
}
/*递归*/
//前序遍历
public static void preOrder(List<String> list,Tree root){
if(root==null){
return;
}
list.add(root.value);
preOrder(list,root.left);
preOrder(list,root.right);
}
//中序遍历
public static void inOrder(List<String> list,Tree root){
if(root==null){
return;
}
inOrder(list,root.left);
list.add(root.value);
inOrder(list,root.right);
}
//后序遍历
public static void afterOrder(List<String> list,Tree root){
if(root==null){
return;
}
afterOrder(list,root.left);
afterOrder(list,root.right);
list.add(root.value);
}
/*非递归*/
//前序遍历
public static List<String> preOrder1(Tree root) {
ArrayList<String> list = new ArrayList<>();
Stack<Tree> stack = new Stack<>();
Tree pre=root;
while(pre!=null||!stack.isEmpty()){
while(pre!=null){
list.add(pre.value);
stack.push(pre);
pre=pre.left;
}
pre = stack.pop();
pre=pre.right;
}
return list;
}
//中序遍历
public static List<String> inOrder1(Tree root) {
List<String> list = new ArrayList<>();
if (root == null) {
return list;
}
Stack<Tree> stack = new Stack<>();
Tree pre=root;
while(pre!=null||!stack.isEmpty()){
while(pre!=null){
stack.push(pre);
pre=pre.left;
}
pre = stack.pop();
list.add(pre.value);
pre=pre.right;
}
return list;
}
//非递归的后序遍历
public static List<String> afterOrder1(Tree root) {
List<String> list = new ArrayList<>();
if (root == null) {
return list;
}
Stack<Tree> stack = new Stack<>();
Tree cur=root;
Tree prev=null;
while(cur!=null||!stack.isEmpty()){
while(cur!=null){
stack.push(cur);
cur=cur.left;
}
Tree top = stack.peek();
if(top.right==null||top.right==prev){
top = stack.pop();
prev=top;
list.add(top.value);
}else{
cur=top.right;
}
}
return list;
}
}
class Tree{
String value;
Tree left;
Tree right;
public Tree(String val, Tree left, Tree right) {
this.value = val;
this.left = left;
this.right = right;
}
public Tree(String val) {
this.value = val;
}
}