递归与二叉树
来源:互联网 发布:php k图 编辑:程序博客网 时间:2024/06/05 05:35
自己动手实现二叉树,特别注意这种树是有排序的,所以数据节点一定要是Comparable 接口的子类才可以,这样方便排序看代码之前,最好了解一下递归推荐博文:http://www.jianshu.com/p/4db970d8ddc11,递归是局部的,只有调用的部分代码才会产生递归,递归下面的代码被称为剩余部分。2,最后的一个递归执行完之后,会释放空间,同时标志着倒数第二个递归的递归部分代码执行完毕,继续执行剩余部分,以此类推,递归的正方向是描述、解决部分问题,反方向是解决剩余问题。3,上面讲的是有递有归,有递无归相对简单,不做阐述package bt;import java.util.Arrays;class BTree { //定义存储数据的节点 class Node{ //当前节点数据 private Comparable data; //存储左节点 private Node left; //存储右节点 private Node right; //数据入口 public Node(Comparable data){ this.data = data; } @SuppressWarnings("unchecked") public void addNode(Node newNode){ if(this.data == null){ return; } //当前节点数据值大于新节点数据值 if(this.data.compareTo(newNode.data) > 0){ //左节点为空,数据存储在左节点 if(this.left == null){ this.left = newNode; }else{ //左节点不为空,递归调用当前增加节点的方法 //递归分两种,有递有归,有递无归,此处属于有递有归,倒着循环增加新节点 this.left.addNode(newNode); } }else{ if(this.right == null){ this.right = newNode; }else{ this.right.addNode(newNode); } } } @SuppressWarnings("unchecked") public void toArrayNode(){ if(this.left != null){ this.left.toArrayNode(); } BTree.this.retData[BTree.this.foot++] = this.data; if(this.right != null){ this.right.toArrayNode(); } } } //设立根结点,像这种数据结构必须有根 private Node root; //计数 private int count = 0; //脚标 private int foot = 0; //存储返回值 private Object []retData; //增加新节点 public void add(Object data){ if(data == null){ return; } Node newNode = new Node((Comparable)data); //根节点为空,将当前节点作为根节点 if(root == null){ root = newNode; }else{ root.addNode(newNode); } //计数 count++; } public Object[] toArray(){ //脚标清零,脚标不清零,第二次get内容的时候,会在原来的基础上增加数组长度,BTree.this.retData[BTree.this.foot++] = this.data;,会导致数据越界 this.foot = 0; this.retData = new Object[this.count]; this.root.toArrayNode(); return this.retData; }}public class Test{ public static void main(String[] args) { BTree bt = new BTree(); bt.add(1); bt.add(2); bt.add(3); bt.add(7); bt.add(6); bt.add(0); System.out.println(Arrays.toString(bt.toArray())); }}运行结果[0, 1, 2, 3, 6, 7]
阅读全文
0 0
- 二叉树与递归
- 递归与二叉树
- 二叉树 递归 与 非递归 遍历
- 递归与非递归二叉树遍历
- 二叉树的递归与非递归
- 二叉树递归与非递归遍历
- 递归与非递归实现二叉树
- 二叉树的递归与非递归
- 二叉树递归与非递归遍历
- 二叉树递归与非递归遍历
- 二叉树递归与非递归遍历
- 二叉树递归与非递归遍历
- 遍历二叉树(递归与非递归)
- 二叉树的递归与非递归
- 【数据结构与算法】二叉树递归与非递归遍历
- 二叉树的创建与遍历(递归)
- 二叉树递归实现与二重指针
- 二叉树的创建与递归遍历
- 黑客-新手入门
- PAT乙级题1016.部分A+B
- Unity3d通过鼠标缩放查看和旋转物体
- 观察者模式
- 编译时缺少openssl/md5.h该怎么处理
- 递归与二叉树
- LeetCode 学习 LinkedList 专项(5)—— Linked List Cycle
- 我所理解的设计模式(C++实现)—— “一句话总结”和索引
- 事件委托技术原理和使用(js,jquery)
- 面向对象笔记
- Ubuntu在vmware虚拟机无法上网的解决方法
- java自动类型转换
- hdu 1255 覆盖的面积(线段树+扫描线)
- 20171015学习《css权威指南》1-6章