数据结构之二叉树

二叉树

1.为什么需要树这种数据结构

  • 数组存储方式的分析�优点:通过下标方式访问元素,速度快。对于有序数组,还可使用二分查找提高检索速度。�缺点:如果要检索具体某个值,或者插入值(按一定顺序)会整体移动,效率较低
  • 链式存储方式的分析�优点:在一定程度上对数组存储方式有优化(比如:插入一个数值节点,只需要将插入节点,链接到链表中即可, 删除效率也很好)。�缺点:在进行检索时,效率仍然较低,比如(检索某个值,需要从头节点开始遍历
  • 树存储方式的分析�能提高数据存储,读取的效率, 比如利用 二叉排序树(Binary Sort Tree),既可以保证数据的检索速度,同时也可以保证数据的插入,删除,修改的速度。

2.树示意图

![1560596464787.png](https://upload-images.jianshu.io/upload_images/7149586-771c0432ec6a3699.png?imageMogr2/auto-orient/strip%7CimageView2/2/w/1240)

3.二叉树的概念

  • 树有很多种,每个节点最多只能有两个子节点的一种形式称为二叉树。
  • 二叉树的子节点分为左节点和右节点。
  • 如果该二叉树的所有叶子节点都在最后一层,并且结点总数= 2^n -1 , n 为层数,则我们称为满二叉树。
  • 如果该二叉树的所有叶子节点都在最后一层或者倒数第二层,而且最后一层的叶子节点在左边连续,倒数第二层的叶子节点在右边连续,我们称为完全二叉树。
![1560601642234.png](https://upload-images.jianshu.io/upload_images/7149586-015059e224c77f99.png?imageMogr2/auto-orient/strip%7CimageView2/2/w/1240)

3.1二叉树遍历

  • 前序遍历: 先输出父节点,再遍历左子树和右子树

  • 中序遍历: 先遍历左子树,再输出父节点,再遍历右子树

  • 后序遍历: 先遍历左子树,再遍历右子树,最后输出父节点

  • 小结: 看输出父节点的顺序,就确定是前序,中序还是后序

3.2代码实现

package cn.smallmartial.tree;

/**
 * @Author smallmartial
 * @Date 2019/6/15
 * @Email smallmarital@qq.com
 */
public class BinaryTreeDemo {
    public static void main(String[] args) {
        //创建一个二叉树
        BinaryTree binaryTree = new BinaryTree();
        HeroNode root = new HeroNode(1, "doodou");
        HeroNode heroNode2 = new HeroNode(2, "smallmartial");
        HeroNode heroNode3 = new HeroNode(3, "张三");
        HeroNode heroNode4 = new HeroNode(4, "李四");

        //先手动创建二叉树
        root.setLeft(heroNode2);
        root.setRiht(heroNode3);
        heroNode3.setRiht(heroNode4);
        binaryTree.setRoot(root);
        System.out.println("前序遍历");
        binaryTree.preOrder();

        System.out.println("中序遍历");
        binaryTree.infixOrder();
        System.out.println("后续序遍历");
        binaryTree.postOrder();
    }
}
//创建二叉树
class BinaryTree{

    private HeroNode root;

    public void setRoot(HeroNode root){
        this.root = root;
    }
    //前序遍历
    public void preOrder(){
        if (this.root != null){
            this.root.proOrder();
        }else {
            System.out.println("二叉树为空,无法遍历");
        }
    }

    //中序遍历
    public void infixOrder(){
        if (this.root != null){
            this.root.infixOrder();
        }else {
            System.out.println("二叉树为空,无法遍历");
        }
    }
    //后续遍历
    public void postOrder(){
        if (this.root != null){
            this.root.postOrder();
        }else {
            System.out.println("二叉树为空,无法遍历");
        }
    }
}

class HeroNode{
    private int no;
    private String name;
    private HeroNode left;
    private HeroNode right;

    public HeroNode(int no, String name) {
        this.no = no;
        this.name = name;
    }

    public int getNo() {
        return no;
    }

    public void setNo(int no) {
        this.no = no;
    }

    public String getName() {
        return name;
    }

    public void setName(String name) {
        this.name = name;
    }

    public HeroNode getLeft() {
        return left;
    }

    public void setLeft(HeroNode left) {
        this.left = left;
    }

    public HeroNode getRiht() {
        return right;
    }

    public void setRiht(HeroNode riht) {
        this.right = riht;
    }

    @Override
    public String toString() {
        return "HeroNode{" +
                "no=" + no +
                ", name='" + name + '\'' +
                ", left=" + left +
                ", riht=" + right +
                '}';
    }
    //前序遍历
    public void proOrder(){
        System.out.println(this);
        //递归向左子树前序遍历
        if (this.left != null){
            this.left.proOrder();
        }
        //递归向右子树前序遍历
        if (this.right != null){
            this.right.proOrder();
        }
        //中序遍历
    }

    //中序遍历
    public void infixOrder(){
        //递归向左子树中序遍历
        if (this.left != null){
            this.left.infixOrder();
        }
        //输出父节点
        System.out.println(this);
        //递归向右子树中序遍历
        if (this.right != null){
            this.right.infixOrder();
        }
    }

    //后序遍历
    public void  postOrder(){
        if (this.left != null){
            this.left.postOrder();
        }
        if (this.right != null){
            this.right.postOrder();
        }
        System.out.println(this);
    }

}

运行结果

3.3二叉树-查找指定节点

  • 要求:
    请编写前序查找,中序查找和后序查找的方法。
    并分别使用三种查找方式,查找 heroNO = 5 的节点
    并分析各种查找方式,分别比较了多少次

  • 代码

    package cn.smallmartial.tree;
    
    /**
     * @Author smallmartial
     * @Date 2019/6/15
     * @Email smallmarital@qq.com
     */
    public class BinaryTreeDemo {
        public static void main(String[] args) {
            //创建一个二叉树
            BinaryTree binaryTree = new BinaryTree();
            HeroNode root = new HeroNode(1, "doodou");
            HeroNode heroNode2 = new HeroNode(2, "smallmartial");
            HeroNode heroNode3 = new HeroNode(3, "张三");
            HeroNode heroNode4 = new HeroNode(4, "李四");
    
            //先手动创建二叉树
            root.setLeft(heroNode2);
            root.setRiht(heroNode3);
            heroNode3.setRiht(heroNode4);
            binaryTree.setRoot(root);
    
    //
    //        System.out.println("前序遍历");
    //        binaryTree.preOrder();
    //
    //        System.out.println("中序遍历");
    //        binaryTree.infixOrder();
    //
    //        System.out.println("后续序遍历");
    //        binaryTree.postOrder();
    
            //前序遍历
            System.out.println("前序遍历方式");
            HeroNode resNode = binaryTree.preOrderSerch(4);
            if (resNode != null){
                System.out.println("找到了信息为no="+resNode.getNo()+"name="+resNode.getName());
            }else {
                System.out.println("没有找到 no ="+5);
            }
        }
    }
    //创建二叉树
    class BinaryTree{
    
        private HeroNode root;
    
        public void setRoot(HeroNode root){
            this.root = root;
        }
        //前序遍历
        public void preOrder(){
            if (this.root != null){
                this.root.proOrder();
            }else {
                System.out.println("二叉树为空,无法遍历");
            }
        }
    
        //中序遍历
        public void infixOrder(){
            if (this.root != null){
                this.root.infixOrder();
            }else {
                System.out.println("二叉树为空,无法遍历");
            }
        }
        //后续遍历
        public void postOrder(){
            if (this.root != null){
                this.root.postOrder();
            }else {
                System.out.println("二叉树为空,无法遍历");
            }
        }
        //前序遍历查找
        public HeroNode preOrderSerch(int no){
            if (root != null){
                return root.proOrderserch(no);
            }else {
                return null;
            }
        }
    
        //中序遍历
        public HeroNode infixOrderSearch(int no){
            if (root != null){
                return root.infixOrderSearch(no);
            }else {
                return null;
            }
        }
        //后续遍历
        public HeroNode postOrderSearch(int no ){
            if (root != null){
                return root.postOrderSerach(no);
            }else {
                return null;
            }
        }
    
    }
    
    class HeroNode{
        private int no;
        private String name;
        private HeroNode left;
        private HeroNode right;
    
        public HeroNode(int no, String name) {
            this.no = no;
            this.name = name;
        }
    
        public int getNo() {
            return no;
        }
    
        public void setNo(int no) {
            this.no = no;
        }
    
        public String getName() {
            return name;
        }
    
        public void setName(String name) {
            this.name = name;
        }
    
        public HeroNode getLeft() {
            return left;
        }
    
        public void setLeft(HeroNode left) {
            this.left = left;
        }
    
        public HeroNode getRiht() {
            return right;
        }
    
        public void setRiht(HeroNode riht) {
            this.right = riht;
        }
    
        @Override
        public String toString() {
            return "HeroNode{" +
                    "no=" + no +
                    ", name='" + name + '\'' +
                    ", left=" + left +
                    ", riht=" + right +
                    '}';
        }
        //前序遍历
        public void proOrder(){
            System.out.println(this);
            //递归向左子树前序遍历
            if (this.left != null){
                this.left.proOrder();
            }
            //递归向右子树前序遍历
            if (this.right != null){
                this.right.proOrder();
            }
            //中序遍历
        }
    
        //中序遍历
        public void infixOrder(){
            //递归向左子树中序遍历
            if (this.left != null){
                this.left.infixOrder();
            }
            //输出父节点
            System.out.println(this);
            //递归向右子树中序遍历
            if (this.right != null){
                this.right.infixOrder();
            }
        }
    
        //后序遍历
        public void  postOrder(){
            if (this.left != null){
                this.left.postOrder();
            }
            if (this.right != null){
                this.right.postOrder();
            }
            System.out.println(this);
        }
    
        //前序遍历查找
        public HeroNode proOrderserch(int no){
            if (this.no == no){
                return this;
            }
    
            HeroNode resNode = null;
            if (this.left != null){
                resNode = this.left.proOrderserch(no);
            }
    
            if (resNode != null){
                return resNode;
            }
    
            if (this.right != null){
                resNode = this.right.proOrderserch(no);
            }
            return resNode;
        }
    
        //中序遍历查找
        public  HeroNode infixOrderSearch(int no){
    
            HeroNode resNode = null;
            if (this.left != null){
                resNode = this.left.infixOrderSearch(no);
            }
    
            if (resNode != null){
                return resNode;
            }
    
            if (this.no == no){
                return this;
            }
    
            if (this.right != null){
                resNode = this.right.infixOrderSearch(no);
            }
            return resNode;
        }
    
        //后序遍历
        public HeroNode postOrderSerach(int no ){
            HeroNode resNode = null;
            if (this.left != null){
                resNode = this.left.infixOrderSearch(no);
            }
    
            if (resNode != null){
                return resNode;
            }
            if (this.right != null){
                resNode = this.right.infixOrderSearch(no);
            }
    
            if (this.no == no){
                return this;
            }
            return resNode;
    
        }
    
    }
    
    

3.4二叉树的删除

  • 如果删除的节点是叶子节点,则删除该节点
    如果删除的节点是非叶子节点,则删除该子树.
    测试,删除掉 5号叶子节点 和 3号子树.

  • 代码

    package cn.smallmartial.tree;
    
    /**
     * @Author smallmartial
     * @Date 2019/6/15
     * @Email smallmarital@qq.com
     */
    public class BinaryTreeDemo {
        public static void main(String[] args) {
            //创建一个二叉树
            BinaryTree binaryTree = new BinaryTree();
            HeroNode root = new HeroNode(1, "doodou");
            HeroNode heroNode2 = new HeroNode(2, "smallmartial");
            HeroNode heroNode3 = new HeroNode(3, "张三");
            HeroNode heroNode4 = new HeroNode(4, "李四");
    
            //先手动创建二叉树
            root.setLeft(heroNode2);
            root.setRiht(heroNode3);
            heroNode3.setRiht(heroNode4);
            binaryTree.setRoot(root);
    
    //
    //        System.out.println("前序遍历");
    //        binaryTree.preOrder();
    //
    //        System.out.println("中序遍历");
    //        binaryTree.infixOrder();
    //
    //        System.out.println("后续序遍历");
    //        binaryTree.postOrder();
    
    //        //前序遍历
    //        System.out.println("前序遍历方式");
    //        HeroNode resNode = binaryTree.preOrderSerch(4);
    //        if (resNode != null){
    //            System.out.println("找到了信息为no="+resNode.getNo()+"name="+resNode.getName());
    //        }else {
    //            System.out.println("没有找到 no ="+5);
    //        }
    
            //测试删除
    
            System.out.println("删除前");
            binaryTree.preOrder();
            binaryTree.delNode(4);
            System.out.println("删除后");
            binaryTree.preOrder();
        }
    }
    //创建二叉树
    class BinaryTree{
    
        private HeroNode root;
    
        public void setRoot(HeroNode root){
            this.root = root;
        }
    
        public void delNode(int no){
            if (root != null){
                if (root.getNo() == no){
                    root = null;
                }else {
                    root.delNode(no);
                }
            }
        }
        //前序遍历
        public void preOrder(){
            if (this.root != null){
                this.root.proOrder();
            }else {
                System.out.println("二叉树为空,无法遍历");
            }
        }
    
        //中序遍历
        public void infixOrder(){
            if (this.root != null){
                this.root.infixOrder();
            }else {
                System.out.println("二叉树为空,无法遍历");
            }
        }
        //后续遍历
        public void postOrder(){
            if (this.root != null){
                this.root.postOrder();
            }else {
                System.out.println("二叉树为空,无法遍历");
            }
        }
        //前序遍历查找
        public HeroNode preOrderSerch(int no){
            if (root != null){
                return root.proOrderserch(no);
            }else {
                return null;
            }
        }
    
        //中序遍历
        public HeroNode infixOrderSearch(int no){
            if (root != null){
                return root.infixOrderSearch(no);
            }else {
                return null;
            }
        }
        //后续遍历
        public HeroNode postOrderSearch(int no ){
            if (root != null){
                return root.postOrderSerach(no);
            }else {
                return null;
            }
        }
    
    }
    
    class HeroNode{
        private int no;
        private String name;
        private HeroNode left;
        private HeroNode right;
    
        public HeroNode(int no, String name) {
            this.no = no;
            this.name = name;
        }
    
        public int getNo() {
            return no;
        }
    
        public void setNo(int no) {
            this.no = no;
        }
    
        public String getName() {
            return name;
        }
    
        public void setName(String name) {
            this.name = name;
        }
    
        public HeroNode getLeft() {
            return left;
        }
    
        public void setLeft(HeroNode left) {
            this.left = left;
        }
    
        public HeroNode getRiht() {
            return right;
        }
    
        public void setRiht(HeroNode riht) {
            this.right = riht;
        }
    
        @Override
        public String toString() {
            return "HeroNode{" +
                    "no=" + no +
                    ", name='" + name + '\'' +
                    ", left=" + left +
                    ", riht=" + right +
                    '}';
        }
    
        //递归删除节点
        public void delNode(int no){
    
            if (this.left != null &&this.left.no == no){
                this.left = null;
                return;
            }
    
            if (this.right != null && this.right.no == no){
                this.right = null;
                return;
            }
            //向左子树递归删除
            if (this.left != null){
                this.left.delNode(no);
            }
    
            //向右递归删除
            if (this.right != null){
                this.right.delNode(no);
            }
    
    
        }
        //前序遍历
        public void proOrder(){
            System.out.println(this);
            //递归向左子树前序遍历
            if (this.left != null){
                this.left.proOrder();
            }
            //递归向右子树前序遍历
            if (this.right != null){
                this.right.proOrder();
            }
            //中序遍历
        }
    
        //中序遍历
        public void infixOrder(){
            //递归向左子树中序遍历
            if (this.left != null){
                this.left.infixOrder();
            }
            //输出父节点
            System.out.println(this);
            //递归向右子树中序遍历
            if (this.right != null){
                this.right.infixOrder();
            }
        }
    
        //后序遍历
        public void  postOrder(){
            if (this.left != null){
                this.left.postOrder();
            }
            if (this.right != null){
                this.right.postOrder();
            }
            System.out.println(this);
        }
    
        //前序遍历查找
        public HeroNode proOrderserch(int no){
            if (this.no == no){
                return this;
            }
    
            HeroNode resNode = null;
            if (this.left != null){
                resNode = this.left.proOrderserch(no);
            }
    
            if (resNode != null){
                return resNode;
            }
    
            if (this.right != null){
                resNode = this.right.proOrderserch(no);
            }
            return resNode;
        }
    
        //中序遍历查找
        public  HeroNode infixOrderSearch(int no){
    
            HeroNode resNode = null;
            if (this.left != null){
                resNode = this.left.infixOrderSearch(no);
            }
    
            if (resNode != null){
                return resNode;
            }
    
            if (this.no == no){
                return this;
            }
    
            if (this.right != null){
                resNode = this.right.infixOrderSearch(no);
            }
            return resNode;
        }
    
        //后序遍历
        public HeroNode postOrderSerach(int no ){
            HeroNode resNode = null;
            if (this.left != null){
                resNode = this.left.infixOrderSearch(no);
            }
    
            if (resNode != null){
    
                return resNode;
            }
            if (this.right != null){
                resNode = this.right.infixOrderSearch(no);
            }
    
            if (this.no == no){
                return this;
            }
            return resNode;
    
        }
    
    }
    
    
  • 运行结果

1560604802227.png
©著作权归作者所有,转载或内容合作请联系作者
  • 序言:七十年代末,一起剥皮案震惊了整个滨河市,随后出现的几起案子,更是在滨河造成了极大的恐慌,老刑警刘岩,带你破解...
    沈念sama阅读 218,451评论 6 506
  • 序言:滨河连续发生了三起死亡事件,死亡现场离奇诡异,居然都是意外死亡,警方通过查阅死者的电脑和手机,发现死者居然都...
    沈念sama阅读 93,172评论 3 394
  • 文/潘晓璐 我一进店门,熙熙楼的掌柜王于贵愁眉苦脸地迎上来,“玉大人,你说我怎么就摊上这事。” “怎么了?”我有些...
    开封第一讲书人阅读 164,782评论 0 354
  • 文/不坏的土叔 我叫张陵,是天一观的道长。 经常有香客问我,道长,这世上最难降的妖魔是什么? 我笑而不...
    开封第一讲书人阅读 58,709评论 1 294
  • 正文 为了忘掉前任,我火速办了婚礼,结果婚礼上,老公的妹妹穿的比我还像新娘。我一直安慰自己,他们只是感情好,可当我...
    茶点故事阅读 67,733评论 6 392
  • 文/花漫 我一把揭开白布。 她就那样静静地躺着,像睡着了一般。 火红的嫁衣衬着肌肤如雪。 梳的纹丝不乱的头发上,一...
    开封第一讲书人阅读 51,578评论 1 305
  • 那天,我揣着相机与录音,去河边找鬼。 笑死,一个胖子当着我的面吹牛,可吹牛的内容都是我干的。 我是一名探鬼主播,决...
    沈念sama阅读 40,320评论 3 418
  • 文/苍兰香墨 我猛地睁开眼,长吁一口气:“原来是场噩梦啊……” “哼!你这毒妇竟也来了?” 一声冷哼从身侧响起,我...
    开封第一讲书人阅读 39,241评论 0 276
  • 序言:老挝万荣一对情侣失踪,失踪者是张志新(化名)和其女友刘颖,没想到半个月后,有当地人在树林里发现了一具尸体,经...
    沈念sama阅读 45,686评论 1 314
  • 正文 独居荒郊野岭守林人离奇死亡,尸身上长有42处带血的脓包…… 初始之章·张勋 以下内容为张勋视角 年9月15日...
    茶点故事阅读 37,878评论 3 336
  • 正文 我和宋清朗相恋三年,在试婚纱的时候发现自己被绿了。 大学时的朋友给我发了我未婚夫和他白月光在一起吃饭的照片。...
    茶点故事阅读 39,992评论 1 348
  • 序言:一个原本活蹦乱跳的男人离奇死亡,死状恐怖,灵堂内的尸体忽然破棺而出,到底是诈尸还是另有隐情,我是刑警宁泽,带...
    沈念sama阅读 35,715评论 5 346
  • 正文 年R本政府宣布,位于F岛的核电站,受9级特大地震影响,放射性物质发生泄漏。R本人自食恶果不足惜,却给世界环境...
    茶点故事阅读 41,336评论 3 330
  • 文/蒙蒙 一、第九天 我趴在偏房一处隐蔽的房顶上张望。 院中可真热闹,春花似锦、人声如沸。这庄子的主人今日做“春日...
    开封第一讲书人阅读 31,912评论 0 22
  • 文/苍兰香墨 我抬头看了看天上的太阳。三九已至,却和暖如春,着一层夹袄步出监牢的瞬间,已是汗流浃背。 一阵脚步声响...
    开封第一讲书人阅读 33,040评论 1 270
  • 我被黑心中介骗来泰国打工, 没想到刚下飞机就差点儿被人妖公主榨干…… 1. 我叫王不留,地道东北人。 一个月前我还...
    沈念sama阅读 48,173评论 3 370
  • 正文 我出身青楼,却偏偏与公主长得像,于是被迫代替她去往敌国和亲。 传闻我的和亲对象是个残疾皇子,可洞房花烛夜当晚...
    茶点故事阅读 44,947评论 2 355

推荐阅读更多精彩内容

  • 如需转载, 请咨询作者, 并且注明出处.有任何问题, 可以关注我的微博: coderwhy, 或者添加我的微信: ...
    coderwhy阅读 8,866评论 12 35
  • 1. AVL树 AVL树简单来说是带有平衡条件的二叉查找树.传统来说是其每个节点的左子树和右子树的高度最多差1(注...
    fredal阅读 1,832评论 0 4
  • 刚开始学编程,都知道数据结构和算法是很重要的,特别是二叉树,一起来了解下 二叉树 二叉树是一种非常重要的[数据结构...
    老鼠AI大米_Java全栈阅读 183评论 0 1
  • 1.HashMap是一个数组+链表/红黑树的结构,数组的下标在HashMap中称为Bucket值,每个数组项对应的...
    谁在烽烟彼岸阅读 1,025评论 2 2
  • 自上周实行小组积分制以来,学生的整体感觉有了明显变化。既为了自己,也为了不拖小组的后腿,都积极为小组加分,生怕自己...
    枫之舞韵阅读 139评论 0 0