二叉树的实现-java

二叉树的特性:
1、节点最多拥有2个子树
2、特殊情况下会转换为链表


1、定义节点

package com.example.demo.datastructure.binarytree;import lombok.Data;/** * @anthor ch * @description * @date */@Datapublic class BinaryHeroNode {   private int no;   private String name;   private BinaryHeroNode left;//默认为null   private BinaryHeroNode right;//默认为null   public BinaryHeroNode(int no, String name) {      this.no = no;      this.name = name;   }}

2、二叉树的实现:

/** * @anthor ch * @description 定义二叉树 * @date */@Data@Componentpublic class BinaryTree {   private BinaryHeroNode root;//根节点   public void setRoot(BinaryHeroNode node) {      if(node==null){         return;      }      //判断跟节点是否为空      if(this.root==null){         this.root = node;      }else{         //循环子节点         insert(this.root,node);      }      //旋转   }   private static void insert(BinaryHeroNode root, BinaryHeroNode node){      //判断当前值是大于还是小于节点值      if(node.getNo()<=root.getNo()){         //插入左边,继续判断子左节点是否为空         if(root.getLeft()==null){            //直接插入            root.setLeft(node);         }else{            //递归判断            insert(root.getLeft(),node);         }      }else{         //插入到右边         if(root.getRight()==null){            //直接插入            root.setRight(node);         }else{            //递归判断            insert(root.getRight(),node);         }      }   }}3、测试/** * @anthor ch * @description 二叉树树测试 * @date */@RestController@RequestMapping("/binaryTreeTest")public class BinaryTreeTest {@Autowiredprivate BinaryTree binaryTree;@RequestMapping("/test")public BinaryTree test(@RequestBody BinaryHeroNode avlHeroNode){binaryTree.setRoot(avlHeroNode);return binaryTree;}}4、结果展示

发表评论
留言与评论(共有 0 条评论) “”
   
验证码:

相关文章

推荐文章