二叉树是数据结构中很重要的结构类型,学习数据结构也是深刻学习编程的必由之路,这里咱们简单介绍下我对于二叉树的理解,水平有限,若有错误还请不吝赐教。java
class Node { private int value;//二叉树的值 private Node leftChild;//左孩子节点 private Node rightChild;//右孩子节点 public Node(int value, Node leftChild, Node rightChild) { this.value = value; this.leftChild = leftChild; this.rightChild = rightChild; } }
本次用到的二叉树是顺序二叉树,即判断当前插入的节点值与二叉树中父节点比较,若是value值大于父节点,插入父节点的右子树种,反之,插入左子树种,以此类推,直到找到相应的字节点插入。node
public void insert(int value) { if (parent == null) {//父节点为空判断 Node node = new Node(value, null, null); parent = node; length++; } else { currentPoint = parent;//将当前结点指向父节点 while(true){//循环遍历节点,查找适合的插入位置 if(currentPoint.value>value){ if(currentPoint.leftChild!=null){ currentPoint=currentPoint.leftChild; }else{ currentPoint.leftChild=new Node(value,null,null); length++; break; } }else{ if(currentPoint.rightChild!=null){ currentPoint=currentPoint.rightChild; }else{ currentPoint.rightChild=new Node(value,null,null); length++; break; } } } } }
public String visit(Node node) { sb.append(node.value+"("); if (node.leftChild != null) visit(node.leftChild);//递归遍历左子树 if (node.rightChild != null) visit(node.rightChild);//递归遍历右子树 sb.append(")"); return sb.toString(); }
public class BinaryTree { private Node parent; private Node currentPoint; private StringBuffer sb; private int length=0; class Node { private int value; private Node leftChild; private Node rightChild; public Node(int value, Node leftChild, Node rightChild) { this.value = value; this.leftChild = leftChild; this.rightChild = rightChild; } } public Node getParent(){ return parent; } public BinaryTree() { sb=new StringBuffer(); } public void insert(int value) { if (parent == null) { Node node = new Node(value, null, null); parent = node; length++; } else { currentPoint = parent; while(true){ if(currentPoint.value>value){ if(currentPoint.leftChild!=null){ currentPoint=currentPoint.leftChild; }else{ currentPoint.leftChild=new Node(value,null,null); length++; break; } }else{ if(currentPoint.rightChild!=null){ currentPoint=currentPoint.rightChild; }else{ currentPoint.rightChild=new Node(value,null,null); length++; break; } } } } } public String visit(Node node) { sb.append(node.value+"("); if (node.leftChild != null) visit(node.leftChild); if (node.rightChild != null) visit(node.rightChild); sb.append(")"); return sb.toString(); } public int getLength(){ return length; } @Override public String toString() { return visit(parent); } }
public static void main(String[] args) { BinaryTree bt = new BinaryTree(); bt.insert(1); bt.insert(3); bt.insert(2); bt.insert(5); bt.insert(6); bt.insert(7); bt.insert(8); bt.insert(9); bt.insert(10); bt.insert(11); bt.insert(12); bt.insert(13); bt.insert(14); bt.insert(15); System.out.println(bt.getLength()); System.out.println(bt.toString()); }
其中括号表示层级包含关系,编程
个人文章列表
Email:sxh13208803520@gmail.com数据结构