1 public class BinaryTree {
2
3 class Node<T>{
4
5 T data;
6 Node<T> leftTree;
7 Node<T> rightTree;
8
9 public Node(T data) {
10 this.data = data;
11 }
12 }
13 //先序遍历
14 private <T> void DLR(Node<T> node){
15 if(node==null){
16 return;
17 }
18 System.out.println(node.data);
19 DLR(node.leftTree);
20 DLR(node.rightTree);
21 }
22 //中序遍历
23 private <T> void LDR(Node<T> node){
24 if(node==null){
25 return;
26 }
27 DLR(node.leftTree);
28 System.out.println(node.data);
29 DLR(node.rightTree);
30 }
31 //后序遍历
32 private <T> void LRD(Node<T> node){
33 if(node==null){
34 return;
35 }
36 DLR(node.leftTree);
37 DLR(node.rightTree);
38 System.out.println(node.data);
39 }
40
41 }
public class BinaryTree {
class Node<T>{
T data;
Node<T> leftTree;
Node<T> rightTree;
public Node(T data) {
this.data = data;
}
}
//先序遍历 从上到下-从左到右
private <T> void DLR(Node<T> node){
if(node==null){
return;
}
Stack<Node<T>>stack=new Stack<>();
LinkedList<Node<T>>outPut=new LinkedList<>();
stack.push(node);
while (!stack.isEmpty()){
//先从栈中取出节点并存入队列中
outPut.push(node);
//因为接下来是处理左孩子--根据栈的先进后出原理,所以先把右孩子放进栈中再把左孩子放进栈中
if(node.rightTree!=null){
stack.push(node.rightTree);
}
if(node.leftTree!=null){
stack.push(node.leftTree);
}
}
}
//中序遍历--从左到右 从下到上
private <T> void LDR(Node<T> node){
if(node==null){
return;
}
Stack<Node<T>>stack=new Stack<>();
LinkedList<Node<T>>outPut=new LinkedList<>();
Node<T>curNode=node;
while (curNode!=null||!stack.isEmpty()){
while (curNode!=null){
stack.push(curNode);
curNode=curNode.leftTree;
}
curNode=stack.pop();
outPut.push(curNode);
//切换到右边的分支---开始最外面的循环先加入左分支 在处理右分支
curNode=curNode.rightTree;
}
}
//后序遍历--其实就是先序遍历中先放左孩子再放右孩子,然后用栈来保存
private <T> void LRD(Node<T> node){
if(node==null){
return;
}
Stack<Node<T>>stack=new Stack<>();
Stack<Node<T>>outPut=new Stack<>();
stack.push(node);
while (!stack.isEmpty()){
outPut.push(node);
if(node.leftTree!=null){
stack.push(node.leftTree);
}
if(node.rightTree!=null){
stack.push(node.rightTree);
}
}
}
}