Java构建二叉树

笔者初学者遇到的问题:内部类调用,以及一个类如何调用另外一个类的成员变量(忘了,通过设置get,set等),

重点是掌握二叉树的创建,明确知道原理和过程。

/**
 * @program: entrance_exam
 * @description: 求二叉树的节点的个数
 * @author: TAO
 * @create: 2018-05-23 09:47
 **/

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

/**算法思想:基于后序遍历的思想遍历,若非空节点,则计数++,否则继续遍历
 *            若根节点为空,那么返回为0.
 * */
class BinaryTree{
    private int []arr={1,2,3,4,5,6,7,8,9};//定义初始数组,插入到二叉树中
    private List<Node> nodeList=null;
    private int count=0;
    //内部类:定义节点
    class Node{
        int data;
        Node lchild;
        Node rchild;

        Node(int data){
            lchild=null;
            rchild=null;
            this.data=data;
        }
    }
    public void createBinTree(){
        nodeList=new LinkedList<>();
        for(int i=0;i<arr.length;i++)
            nodeList.add(new Node(arr[i]));//将数组中的每一个值转换为节点
        for (int parentIndex = 0; parentIndex < arr.length / 2 - 1; parentIndex++) {
            // 左孩子
            nodeList.get(parentIndex).lchild = nodeList.get(parentIndex * 2 + 1);
            // 右孩子
            nodeList.get(parentIndex).rchild = nodeList.get(parentIndex * 2 + 2);
        }
        // 最后一个父节点:因为最后一个父节点可能没有右孩子,所以单独拿出来处理
        int lastParentIndex = arr.length / 2 - 1;
        // 左孩子
        nodeList.get(lastParentIndex).lchild = nodeList.get(lastParentIndex * 2 + 1);
        // 右孩子,如果数组的长度为奇数才建立右孩子
        if (arr.length % 2 == 1) {
            nodeList.get(lastParentIndex).rchild = nodeList.get(lastParentIndex * 2 + 2);
        }
    }
    public void  postOrderTraverse(Node node) {
        if (node == null)
            return ;
        postOrderTraverse(node.lchild);
        postOrderTraverse(node.rchild);
        System.out.printf("%3d",node.data);
        count++;
    }

    public List<Node> getNodeList() {
        return nodeList;
    }

    public int getCount() {
        return count;
    }
}
public class Entrance7 {
    public static void main(String[] args) {
        BinaryTree binaryTree=new BinaryTree();
        binaryTree.createBinTree();
        BinaryTree.Node root=binaryTree.getNodeList().get(0);
        binaryTree.postOrderTraverse(root);
        System.out.println();
        System.out.println(binaryTree.getCount());
    }
}

猜你喜欢

转载自blog.csdn.net/sir_ti/article/details/80417038