数据结构--------二叉树的增删查改

public class Node {
    public Node right;
    public Node left;
    public int data;

    public Node(int data) {
        this.data = data;
    }

    public Node() {
    }
}

 

/**
 * 二叉树方法:
 *   (1)遍历:
 *       1. 前序遍历
 *       2. 中序遍历
 *       3. 后序遍历
 *       4. 层次遍历
 *    (2)插入
 *    (3)二分查找
 *    (4)删除
 *    (5)返回树的深度:  BFS和递归
 *
 */
public class Tree {

    private Node root;
    private int length; //节点数

    public Tree() {
        root = null;
        this.length = 0;
    }

    public int getLength() {
        return length;
    }

    public boolean isEmpty(){
        return root == null;
    }

    /**
     * 插入
     * @param data
     */
    public void insert(int data){
        Node newNode = new Node(data);

        //第一种情况:  第一个节点
        if (isEmpty()){
            root = newNode;
            length++;
            return ;
        }

        Node rootNode = root;
        while (true){
            if (data > rootNode.data){
                if (rootNode.right == null){
                    rootNode.right = newNode;
                    length++;
                    return ;
                }
                rootNode = rootNode.right;
            }else {
                if (rootNode.left == null){
                    rootNode.left = newNode;
                    length++;
                    return ;
                }
                rootNode = rootNode.left;
            }
        }
    }


    public void print(){

        System.out.println("前序遍历: ");
        preOrder(root);
        System.out.println("中序遍历: ");
        inOrder(root);
        System.out.println("后序遍历: ");
        postOrder(root);

    }

    /**
     * 前序遍历
     * @param node
     */
    private void preOrder(Node n
  • 0
    点赞
  • 3
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值