java实现二叉树的构建以及三种遍历

一、把一个数组的值赋给二叉树

1.1二叉树的构建

 

 1.2 具体代码

package com.algo.binarytree;

import java.util.LinkedList;
import java.util.List;

public class BinTreeTraverse {
    
    private int [] array = {1,2,3,4,5,6,7,8,9};
    private static List<Node> nodeList = null;
    
    /**
     * 内部类
     * @param args
     */
    private static class Node{
        Node left;
        Node right;
        int data;
        Node(int newData){
            left = null;
            right = null;
            data = newData;
        }
    }
    
    public void createBinTree() {
        nodeList = new LinkedList<Node>();
        //将数组的值一次转为Node节点
        for(int nodeIndex = 0;nodeIndex<array.length;nodeIndex++) {
            nodeList.add(new Node(array[nodeIndex]));
        }
        // 对前lastParentIndex-1个父节点按照父节点与孩子节点的数字关系建立二叉树
        for(int parentIndex = 0;parentIndex<array.length/2-1;parentIndex++) {
            //左孩子
            nodeList.get(parentIndex).left = nodeList.get(parentIndex*2+1);
            //右孩子
            nodeList.get(parentIndex).right = nodeList.get(parentIndex*2+2);
        }
        //最后一个父节点:因为最后一个父节点可能没有右孩子,所以单独拿出来处理
        int lastParentIndex = array.length/2-1;
        //左孩子
        nodeList.get(lastParentIndex).left = nodeList.get(lastParentIndex*2+1);
        //右孩子
        if(array.length%2==1) {
            nodeList.get(lastParentIndex).right = nodeList.get(lastParentIndex*2+2);
        }
        
        
    }
    //前序遍历,根左右
    public static void preOrderTraverse(Node node) {
        if(node == null) {
            return ;
        }
        System.out.print(node.data + " ");
        preOrderTraverse(node.left);
        preOrderTraverse(node.right);
    }
    
    //中序遍历,左根右
    public static void inOrderTraverse(Node node) {
        if(node==null) {
            return;
        }
        preOrderTraverse(node.left);
        System.out.print(node.data + " ");
        preOrderTraverse(node.right);
    }
    
    //后序遍历,左右根
    public static void postOrderTraverse(Node node) {
        if(node == null) {
            return ;
        }
        postOrderTraverse(node.left);
        postOrderTraverse(node.right);
        System.out.print(node.data + " ");
    }

    public static void main(String[] args) {
        // TODO Auto-generated method stub
        BinTreeTraverse binTree = new BinTreeTraverse();
        binTree.createBinTree();
        Node root = nodeList.get(0);
        
        
        System.out.println("先序遍历:");  
        preOrderTraverse(root);  
        System.out.println();  
  
        System.out.println("中序遍历:");  
        inOrderTraverse(root);  
        System.out.println();  
  
        System.out.println("后序遍历:");  
        postOrderTraverse(root);
        

    }

}

 

输出结果:

先序遍历:
1 2 4 8 9 5 3 6 7 
中序遍历:
2 4 8 9 5 1 3 6 7 
后序遍历:
8 9 4 5 2 6 7 3 1 

 

posted @ 2020-06-02 05:55  alittlecomputer  阅读(423)  评论(0编辑  收藏  举报