import java.util.Stack;
class BinaryNode{
Object element;
BinaryNode left;
BinaryNode right;
public BinaryNode(Object element,BinaryNode left,BinaryNode right){
this.element = element;
this.left = left;
this.right = right;
}
}
public class SyncObject {
//递归的前、中、后排序
public static void pre(BinaryNode b){
if(b==null)return;
System.out.print(b.element);
pre(b.left);
pre(b.right);
}
public static void in(BinaryNode b){
if(b==null)return;
in(b.left);
System.out.print(b.element);
in(b.right);
}
public static void aft(BinaryNode b){
if(b==null)return;
aft(b.left);
aft(b.right);
System.out.print(b.element);
}
//非递归的前、中、后排序,需要堆栈存储信息
public static void nPre(BinaryNode b){
Stack<BinaryNode> stack = new Stack<BinaryNode>();
while (b!=null||!stack.isEmpty()) {
if(b!=null){
System.out.print(b.element);
stack.push(b);
b=b.left;
}else{
b = stack.pop();
b=b.right;
}
}
}
public static void nIn(BinaryNode b){
Stack<BinaryNode> stack = new Stack<BinaryNode>();
while (b!=null||!stack.isEmpty()) {
if(b!=null){
stack.push(b);
b=b.left;
}else{
b = stack.pop();
System.out.print(b.element);
b=b.right;
}
}
}
public static void nAft(BinaryNode b){
Stack<BinaryNode> stack = new Stack<BinaryNode>();
Stack<BinaryNode> temp = new Stack<BinaryNode>();
while (b!=null||!stack.isEmpty()) {
if(b!=null){
stack.push(b);
temp.push(b);
b=b.right;
}else{
b=stack.pop();
b=b.left;
}
}
while (!temp.isEmpty()) {
System.out.print(temp.pop().element);
}
}
public static void main(String[] args) throws InterruptedException, CloneNotSupportedException {
BinaryNode dNode = new BinaryNode("D", null, null);
BinaryNode eNode = new BinaryNode("E", null, null);
BinaryNode fNode = new BinaryNode("F", null, null);
BinaryNode gNode = new BinaryNode("G", null, null);
BinaryNode bNode = new BinaryNode("B", dNode, eNode);
BinaryNode cNode = new BinaryNode("C", fNode, gNode);
BinaryNode root = new BinaryNode("A", bNode, cNode);
pre(root);
System.out.println();
nPre(root);
System.out.println();
System.out.println("--------------------------------");
in(root);
System.out.println();
nIn(root);
System.out.println();
System.out.println("--------------------------------");
aft(root);
System.out.println();
nAft(root);
}
}
二叉树的前、中、后遍历递归和非递归java实现
最新推荐文章于 2021-09-23 21:02:08 发布