二叉树非递归遍历及存储

发布时间 2023-10-21 14:34:32作者: 翎刿

 

import java.util.ArrayList;
import java.util.LinkedList;
import java.util.Scanner;

public class Tree
{
    private int data;
    private Tree lchild;
    private Tree rchild;
    public Tree(){
        this.lchild=null;
        this.rchild=null;
    }
    public Tree(int data){
        this.data=data;
        this.lchild=new Tree();
        this.rchild=new Tree();
    }
    public Tree(Tree node){
        this.data=node.data;
        this.lchild=new Tree();
        this.rchild=new Tree();
    }

    public int getData() {
        return data;
    }

    public void setData(int data) {
        this.data = data;
    }

    public Tree getLchild() {
        return lchild;
    }

    public void setLchild(Tree lchild) {
        this.lchild = lchild;
    }

    public Tree getRchild() {
        return rchild;
    }

    public void setRchild(Tree rchild) {
        this.rchild = rchild;
    }
    public Tree createTree(LinkedList<Character>list){
        Tree node=null;
        char s=list.removeFirst();
        if(s!='#'){
            node=new Tree(s-'0');
            node.lchild=createTree(list);
            node.rchild=createTree(list);
        }
        return node;
    }
    public void Preorder(Tree r){
        Tree[] s=new Tree[100];
        int top=0;
        while(r!=null||top!=0){
            if(r!=null){
                System.out.print(r.getData()+" ");
                s[top]=r;
                top++;
                r=r.getLchild();
            }
            else{
                r=s[top-1];
                top--;
                r=r.getRchild();
            }
        }
    }
    public void Inorder(Tree r){
        Tree[] s=new Tree[100];
        int top=0;
        while(r!=null||top!=0){
            if(r!=null){
                s[top]=r;
                top++;
                r=r.getLchild();
            }
            else {
                r = s[top - 1];
                top--;
                System.out.print(r.getData() + " ");
                r = r.getRchild();
            }
        }

    }
    public void Postorder(Tree r){
        Tree[] s=new Tree[100];
        Tree last=null;
        int top=0;
        while (r!= null||top != 0) {
            if(r!=null){
                s[top]=r;
                top++;
                r=r.getLchild();
            }
            else{
                r=s[top-1];
                if(r.getRchild()!=last&&r.getRchild()!=null){
                    r=r.getRchild();
                    s[top]=r;
                    top++;
                    r=r.getLchild();
                }
                else{
                    System.out.print(r.getData()+" ");
                    top--;
                    last=r;
                    r=null;
                }
            }
        }
    }
}