Java数据结构与算法

Java数据结构:二叉树

2020-07-15  本文已影响0人  Patarw

一、为什么需要树这种数据结构

数组存储方式的分析

链式存储方式的分析

树存储方式的分析

1、二叉树的基本概念

一颗二叉树

1.满二叉树

满二叉树

2.完全二叉树

完全二叉树

3、顺序存储二叉树

顺序存储二叉树在后面的堆排序中也会运用到,所以还是挺重要的

二、创建一颗简单的二叉树

class  BinaryTreeNode{
private int id; //节点序号
private BinaryTreeNode left; //左节点
private BinaryTreeNode right; //右节点
    //构造方法
    public  BinaryTreeNode(int id){this.id = id;}
}

为了在其他类中访问到这些字段,我们还需要get和set方法
然后我们在方法里面创建一颗这样子的树:

  public static void main(String[] args) {
        BinaryTreeNode t1 = new BinaryTreeNode(1);
        BinaryTreeNode t2 = new BinaryTreeNode(2);
        BinaryTreeNode t3 = new BinaryTreeNode(3);
        BinaryTreeNode t4 = new BinaryTreeNode(4);
        BinaryTreeNode t5 = new BinaryTreeNode(5);
        BinaryTreeNode t6 = new BinaryTreeNode(6);
        BinaryTreeNode t7 = new BinaryTreeNode(7);   //先new出7个节点      

        //然后在把他们连接起来
    t1.setLeft(t2);
    t1.setRight(t3);   //表示父节点1的左右节点
    
    t2.setLeft(t4);
    t2.setRight(t5);  //表示2的左右节点

    t3.setLeft(t6);
    t3.setRight(t7);  //表示3的左右节点
    //因为4、5、6、7都是叶子节点,叶子节点的左右节点都为null,所以不需要set
    }

遍历一颗二叉树

遍历二叉树有三种方式:

在main方法中使用t1.pre();遍历结果如下:

在main方法中使用t1.mid();遍历结果如下:

在main方法中使用t1.next();遍历结果如下:

查找二叉树中的值

二叉树的查找也分为前、中、后序,因为大体思想和遍历差不多,我这里也只上前序查找的代码了:

      //前序查找
  public BinaryTreeNode preFind(int id) {
    BinaryTreeNode res = null;
    if(this.id == id) {
        return this;
    }
    if(this.left != null) {
        res = this.left.preFind(id);
    }
    if(res != null) {
        return res;
    }
    if(this.right != null) {
        res = this.right.preFind(id);
    }
    return res;             
}
上一篇 下一篇

猜你喜欢

热点阅读