zoukankan      html  css  js  c++  java
  • 完全二叉树的构建及三种遍历

    package cn.demo;
    import java.util.LinkedList;
    import java.util.List;

    //二叉树的定义,孩子表示法
    public class BinTreeTraverse2 {

    //定义一个数字,将数组转换为完全二叉树
        private int[] array={1,2,3,4,5,6,7,8,9};

    //定义一个存放节点的list集合
        private  List<Node>nodeList=null;

    //节点的定义
          class Node{
            Node leftChild;
            Node rightChild;
            int data;
            Node(int newData){
                leftChild=null;
                rightChild=null;
                data=newData;
            }
        }
        public List<Node> getNodeList() {
            return nodeList;
        }
        public void createBinTree(){
            nodeList=new LinkedList<Node>();

        //将数组的值,转换成树中节点的值
            for(int parentIndex=0;parentIndex < array.length;parentIndex++){
                nodeList.add(new Node(array[parentIndex]));
            }
            for(int parentIndex=0;parentIndex<array.length/2-1;parentIndex++){
                nodeList.get(parentIndex).leftChild=nodeList.get(parentIndex*2+1);
                nodeList.get(parentIndex).rightChild=nodeList.get(parentIndex*2+2);
            }
            int lastParentIndex=array.length/2-1;
            nodeList.get(lastParentIndex).leftChild=nodeList.get(lastParentIndex*2+1);
            if(array.length%2==1){
                nodeList.get(lastParentIndex).rightChild=nodeList.get(lastParentIndex*2+2);
            }
            
        }

    //二叉树的前序遍历
        public  void preOrderTraverse(Node node){
            if(node==null)
                return;
            System.out.print(node.data+"  ");
            preOrderTraverse(node.leftChild);
            preOrderTraverse(node.rightChild);
        }

    //二叉树的中序遍历
        public  void preOrderTraverse(Node node){
            if(node==null)
                return;
          
            preOrderTraverse(node.leftChild);

         System.out.print(node.data+"  ");
            preOrderTraverse(node.rightChild);
        }

    //二叉树的后序遍历
        public  void preOrderTraverse(Node node){
            if(node==null)
                return;
          
            preOrderTraverse(node.leftChild);
            preOrderTraverse(node.rightChild);

        System.out.print(node.data+"  ");
        }
    }

  • 相关阅读:
    [C++]多源最短路径(带权有向图):【Floyd算法(动态规划法)】 VS n*Dijkstra算法(贪心算法)
    [C++]Yellow Cards
    [C++]哈夫曼树(最优满二叉树) / 哈夫曼编码(贪心算法)
    考研部分复习策略记录
    [C++/JavaScript]数据结构:栈和数列>案例引入(数制的转换)
    [C++]数据结构:线性表之(单)链表
    [C++]数据结构:线性表之顺序表
    自然语言处理(NLP)之个人小结
    NLP之TF-IDF与BM25原理探究
    [Python]Excel编程示例教程(openpyxl)
  • 原文地址:https://www.cnblogs.com/2nao/p/6416738.html
Copyright © 2011-2022 走看看