java 实现二叉树的基本操作

时间:2021-11-29 23:09:10


我建立的二叉树如下图所示:

java 实现二叉树的基本操作


以下是使用Java语言实现二叉树的基本操作

 
package com.ddh.binarytree;



import java.util.*;

@SuppressWarnings("all")


public class BinaryTree {
    private TreeNode root=null;
    public BinaryTree(){
        root=new TreeNode(1,"A");
    }
    /*
    * 创建二叉树
    * */
    public void createBinaryTree(){
        TreeNode nodeB=new TreeNode(2,"B");
        TreeNode nodeC=new TreeNode(3,"C");
        TreeNode nodeD=new TreeNode(4,"D");
        TreeNode nodeE=new TreeNode(5,"E");
        TreeNode nodeF=new TreeNode(6,"F");
        root.leftChild=nodeB;
        root.rightChild=nodeC;
        nodeB.leftChild=nodeD;
        nodeB.rightChild=nodeE;
        nodeC.rightChild=nodeF;
    }

    /**  * 二叉树的创建  * @param data  */  public void createBinaryTreePre (ArrayList<String> data ){
        createBinaryTreePre(data.size(),data);
    }

    private TreeNode createBinaryTreePre(int size, ArrayList<String> data) {
        if (data.size()==0){
            return null;
        }
        Object d=data.get(0);
        TreeNode node;
        int index=size-data.size();
        if (d.equals("#")){
            node=null;
            data.remove(0);
            return node;
        }
        node=new TreeNode(index,d);
        if (index==0){
            root=node;
        }
        data.remove(0);
        node.leftChild=createBinaryTreePre(size,data);
        node.rightChild=createBinaryTreePre(size,data);
        return node;
    }

    /**  * 求二叉树的高度  * @param <T>
     */  public int getHeight(){
        return getHeight(root);
    }
    private int getHeight(TreeNode root){
        if (root==null) {
            return 0;
        }else{
            int i=getHeight(root.leftChild);
            int j=getHeight(root.rightChild);
            return (i<j)?j+1:i+1;
        }
    }

    /**  * 求二叉树的节点数  * @param  *  */  public int getSize(){
        return getSize(root);
    }

    /**  *  * @param root  * @return  */  private int getSize(TreeNode root) {
        if (root==null){
            return 0;
        }else{
            return 1+getSize(root.leftChild)+getSize(root.rightChild);
        }
    }

    /**  * 前序遍历递归实现  * @param <T>
     */  public void preOrder(TreeNode root){
        if (root==null){
            return;
        }else{
            System.out.print(root.getData()+"  ");
            preOrder(root.leftChild);
            preOrder(root.rightChild);
        }
    }

    /**  * 中序递归实现遍历二叉树  * @param root  */  public void midOrder(TreeNode root){
        if (root==null){
            return;
        }else {
            midOrder(root.leftChild);
            System.out.print ( root.getData()+"  ");
            midOrder(root.rightChild);
        }
    }

    /**  * 后序递归遍历二叉树  * @param root  */  public void postOrder(TreeNode root){
        if (root==null){
            return;
        }else {
            postOrder(root.leftChild);
            postOrder(root.rightChild);
            System.out.print( root.getData()+"  ");
        }
    }

    /**  * 先序非递归遍历二叉树  * @param root  */  public void PreOder1(TreeNode root){
          if(root == null){
              return;
          }
          Stack<TreeNode> stack = new Stack<TreeNode>();
          stack.push(root);
          while(!stack.isEmpty()){
              //出栈和进栈
              TreeNode node= stack.pop();//弹出根结点
              //压入子结点
              System.out.print ( node.getData()+"  ");
              if(node.rightChild!=null){
                  stack.push(node.rightChild);

              }
              if(node.leftChild!=null){
                  stack.push(node.leftChild);
              }
          }
      }
    /**  * 中序非递归遍历二叉树  * @param root  */  public void midOrder1(TreeNode root){
       if (root==null){
           return;
       }
        Stack<TreeNode> stack=new Stack<>();
        TreeNode p=root;
        while (p!=null ||!stack.isEmpty()){
            while (p!=null){
                stack.push(p);
                p=p.leftChild;
            }
            if (!stack.isEmpty()){
                 p=stack.pop();
                System.out.print(p.getData()+"  ");
                p=p.rightChild;
            }
        }
    }

    /**  * 二叉树的非递归后序遍历  * @param root  */  public void postOrder1(TreeNode root){
         if (root==null){
             return;
         }
         Stack<TreeNode> stack=new Stack<>();
        TreeNode p,q;
        p=root;q=null;
        while (p!=null||!stack.isEmpty()){
            while (p!=null){
                stack.push(p);p=p.leftChild;
            }
            if (!stack.isEmpty()){
                p=stack.peek();
                if (p.rightChild==null||p.rightChild==q){
                    stack.pop();
                    System.out.print(p.getData()+"  ");
                    q=p;
                    p=null;
                }else {
                    p=p.rightChild;
                }
            }
        }
    }
    /**  * 二叉树的层次遍历  * @param root  */  public void levelOrder(TreeNode root){
        Queue<TreeNode> queue=new ArrayDeque<>();
        TreeNode p=root;
        queue.add(p);
        while (!queue.isEmpty()){
            p=queue.poll();
            System.out.print(p.getData()+" ");
            if (p.leftChild!=null){
                queue.add(p.leftChild);
            }
            if (p.rightChild!=null){
                queue.add(p.rightChild);
            }
        }
    }

    /**  * 二叉树的叶子节点遍历  * @param root  */  public void leafOrder(TreeNode root){

        if (root != null) {
            if (root.leftChild == null && root.rightChild == null) {
                System.out.print(root.getData()+"  ");
            }
            leafOrder(root.leftChild);
            leafOrder(root.rightChild);
        }

    }

    /**  * 获得叶子节点的数目  * @return  */  public int getLeafNum(){
        return getLeafNum(root);
    }
    private int getLeafNum(TreeNode root) {
        if (root != null) {
            if (root.leftChild == null && root.rightChild == null) {
                return 1;
            }
            return getLeafNum(root.leftChild) + getLeafNum(root.rightChild);
        }
        return 0;
    }
    public class TreeNode<T>{
        private int index;
        private T data;
        private TreeNode  leftChild;
        private TreeNode  rightChild;
        public TreeNode(int index,T data){
            this.index=index;
            this.data=data;
            this.leftChild=null;
            this.rightChild=null;
        }

        public int getIndex() {
            return index;
        }

        public void setIndex(int index) {
            this.index = index;
        }

        public T getData() {
            return data;
        }

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



    public static void main(String[] args) {
        BinaryTree tree=new BinaryTree();
       ArrayList<String> lists=new ArrayList();
        String[] s=new String[]{"A","B","D","#","#","E","#","#","C","#","F","#","#"};
        for (String str:s){
            lists.add(str);
        }
        tree.createBinaryTreePre(  lists);
        System.out.println("二叉树的递归先序遍历结果为:");
        System.out.print("preOder data: ");
        tree.preOrder(tree.root);
        System.out.println();
        System.out.println("二叉树的递归中序遍历结果为:");
        System.out.print("midOder data: ");
        tree.midOrder(tree.root);
        System.out.println();
        System.out.println("二叉树的递归后序遍历结果为:");
        System.out.print("postOder data: ");
        tree.postOrder(tree.root);
        System.out.println();
        System.out.println("二叉树的非递归先序遍历遍历结果为:");
        System.out.print("nonpreOder data: ");
       tree.PreOder1(tree.root);
        System.out.println();
        System.out.println("二叉树的非递归中序遍历遍历结果为:");
        System.out.print("nonmidOder data: ");
        tree.midOrder1(tree.root);
        System.out.println();
        System.out.println("二叉树的非递归后序遍历遍历结果为:");
        System.out.print("nonmidOder data: ");
        tree.postOrder1(tree.root);
        System.out.println();
        System.out.println("二叉树数的高度为: "+tree.getHeight());
        System.out.println("二叉树的节点数为: "+tree.getSize());
        System.out.println("二叉树的层次遍历结果为:");
        System.out.print("levelOrder: ");
        tree.levelOrder(tree.root);
        System.out.println();
        System.out.println("二叉树的叶子节点遍历结果为:");
        System.out.print("leafOrder: ");
         tree.leafOrder(tree.root);
        System.out.println();
        System.out.println("叶子节点的数目: "+tree.getLeafNum());
    }
}

执行结果如下所示
java 实现二叉树的基本操作