【算法】二叉树的前序遍历、中序遍历和后序遍历

我们构建一个如下图所示的二叉树:

首先构建出来这个数据结构:

 1 package main;
 2 
 3 public class Node {
 4     private String name = "";
 5     public Node leftChild;
 6     public Node rightChild;
 7     public Node(String name){
 8         this.name = name;
 9     }
10 
11     public String read(){
12         String result = "";
13         //result+=name; //前序遍历
14         if(leftChild != null){
15             result += leftChild.read();
16         }
17         //result+=name; 中序遍历
18         if(rightChild != null){
19             result+= rightChild.read();
20         }
21         result+=name; //后序遍历
22         return result;
23     }
24 }
 1 package main;
 2 
 3 import java.util.ArrayList;
 4 import java.util.Stack;
 5 import java.util.concurrent.ExecutorService;
 6 import java.util.concurrent.Executors;
 7 import java.util.concurrent.locks.Condition;
 8 import java.util.concurrent.locks.Lock;
 9 import java.util.concurrent.locks.ReentrantLock;
10 
11 public class Main {
12     public static void main(String[] args){
13         Node a = new Node("A");
14         Node b = new Node("B");
15         Node c = new Node("C");
16         Node d = new Node("D");
17         Node e = new Node("E");
18         Node f = new Node("F");
19         Node g = new Node("G");
20         Node h = new Node("H");
21         Node i = new Node("I");
22         a.leftChild = b;
23         a.rightChild = c;
24         b.leftChild = d;
25         d.leftChild = g;
26         d.rightChild = h;
27         c.leftChild = e;
28         c.rightChild = f;
29         e.rightChild = i;
30         System.out.println(a.read());
31     }
32 
33 }

猜你喜欢

转载自www.cnblogs.com/yanyojun/p/9488452.html