二叉樹是數據結構中很重要的結構類型,學習數據結構也是深刻學習編程的必由之路,這裏咱們簡單介紹下我對於二叉樹的理解,水平有限,若有錯誤還請不吝賜教。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數據結構