【Java】二叉树

如果以数据结构为例,我觉得需要掌握的有:会使用递归、数组操作、链表、树、图。

其中,树是一个很重要的结构。对树的操作需要考虑俩个问题:

  1.一个是数据的存储问题,左右

  2.树的遍历问题:前序、中序、后序

如果要进行二叉树的操作处理往往要使用中序,因为中序是可以排序的。下面实现一个二叉树,同时可以排序。

class BinaryTree{
    private class Node{  
        private Comparable data;//因为数据是要可以比较的所以需要排序
        private Node left;
        private Node right;
        public Node(Comparable data){
            this.data = data;
        }
        public void addNode(Node newNode){
            if(this.data.comparTo(newNode.data)>0){
                if(this.right == null){
                    this.right = newNode;
                }else{
                    this.left.addNode(newNode);
                }
            }else{
                if(this.left == null){
                    this.left = newNode;
                } else{
                    this.left.addNode(newNode);
                }
            }
        }
        public void toArrayNode(){
            if (this.left != null){
                this.left.toArrayNode();
            }
            BinaryTree.this.reObj[BinaryTree.this.foot ++] = this.data;
            if(this.right != null){
                this.right.toArrayNode();
            }
        }

    private Node root; //需要根节点
    private int count; //统计个数
    private int foot;
    private Object reObj[];
    public void add(object data){
        Comparable com = (Comparable) data;
        Node newNode = new Node(com);
        if (this.root == null){
            this.root = newNode;
        }    
        else{
            this.root.addNode(newNode);
        }
        this.count ++;
    }
    public Object[] toArray(){
        if(this.root == null){
            return null;
        }
        this.retObj = new Object[this.count];
        this.root.toArrayNode();
        return this.retObj;
    }
}
原文地址:https://www.cnblogs.com/guangluwutu/p/12300697.html