二叉树的创建、层次遍历、前序遍历、中序遍历、后序遍历

import java.util.ArrayList;
import java.util.LinkedList;
import java.util.Queue;

public class java{
    public static void main(String[] args){
        java Java=new java();
        bitTreeNode root=Java.createTree();
        System.out.println("前序遍历: ");
        Java.preorder(root);
        System.out.println("\n中序遍历:");
        Java.inorder(root);
        System.out.println("\n后序遍历: ");
        Java.lastorder(root);
        System.out.println("\n层次遍历:");
        ArrayList<Object> arrayList=Java.PrintFromTopToBottom(root);
        for (Object o:arrayList){
            System.out.print(o);
        }
    }


    public bitTreeNode createTree(){
        bitTreeNode d = new bitTreeNode('d',null,null);
        bitTreeNode e = new bitTreeNode('e',null,null);
        bitTreeNode f = new bitTreeNode('f',null,null);
        bitTreeNode g = new bitTreeNode('g',null,null);
        bitTreeNode b = new bitTreeNode('b',d,e);
        bitTreeNode c = new bitTreeNode('c',f,g);
        bitTreeNode a = new bitTreeNode('a',b,c);
        return a;
    }
    public ArrayList<Object>  PrintFromTopToBottom(bitTreeNode root){
        ArrayList<Object> arrayList=new ArrayList<>();
        Queue<bitTreeNode> queue=new LinkedList<>();
        if (root!=null){
            queue.offer(root);
        }
        while (!queue.isEmpty()){
            bitTreeNode node=queue.poll();
            arrayList.add(node.val);
            if (node.lchild!=null)
                queue.offer(node.lchild);
            if (node.rchild!=null)
                queue.offer(node.rchild);
        }


        return arrayList;
    }
    public void preorder(bitTreeNode node){
        if (node==null)
            return;
        System.out.print(node.val);
        preorder(node.lchild);
        preorder(node.rchild);
    }
    public void inorder(bitTreeNode node){
        if (node==null)
            return;
        inorder(node.lchild);
        System.out.print(node.val);
        inorder(node.rchild);
    }
    public void lastorder(bitTreeNode node){
        if (node==null)
            return;
        lastorder(node.lchild);
        lastorder(node.rchild);
        System.out.print(node.val);
    }


}
class bitTreeNode{
    Object val;
    bitTreeNode lchild;
    bitTreeNode rchild;
    public bitTreeNode(Object val,bitTreeNode lchild,bitTreeNode rchild){
        this.val=val;
        this.lchild=lchild;
        this.rchild=rchild;
    }
}

 

转载于:https://www.cnblogs.com/hcw110/p/11256625.html

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值