java實現二叉排序樹

來源:互聯網
上載者:User

標籤:二叉樹

什麼是二叉排序樹:二叉排序樹或者是一顆空樹,或者具有以下性質的二叉樹:

(1)若它的左子樹不為空白,則左子樹上的所有節點的值都小於他的父節點的值;

(2)若它的右子樹不為空白,則右子樹上的所有節點的值都大於他的父節點的值;

(3)它的左右子樹也分別為二叉排序樹;

java執行個體:

package com.test.linked;public class HeapSort {public class Node{private int data;private Node leftChildren;private Node rightChildren;public Node(int data){this.data=data;}public String toString(){return " "+data;}}public Node root;/** * 插入結點 * @param in */public void insert(Node in){if(root==null){//當為空白樹時將結點當作根節點root=in;}else{Node current=root;Node parent;//當作parentwhile(current!=null){//當迴圈到空時結束parent=current;if(in.data<current.data){//比當前結點小往左邊走current=current.leftChildren;if(current==null){//當左邊子節點為空白意味著找到了要插入的位置parent.leftChildren=in;}}else{//否則往右邊走current=current.rightChildren;if(current==null){parent.rightChildren=in;}}}}}/** * 尋找元素 * @param key */public void find(int key){Node current=root;int deep=1;if(current!=null){//判斷根節點是否為空白while(current.data!=key){if(key<current.data){//同樣的比該節點小往左邊走否則往右邊走current=current.leftChildren;}else{current=current.rightChildren;}deep++;//尋找的結點在第幾層;if(current==null){System.out.println("Node can't be found");return;}}System.out.println("this Node is :"+current+"at deep:"+deep);}else{System.out.println("this tree is null");}}/** * 遍曆二叉樹(在這裡是先序遍曆)利用遞迴自己遍曆自己,直到所有節點都被遍曆 * @param node */public void display(Node node){if(node!=null){System.out.println(node.data);display(node.leftChildren);display(node.rightChildren);}}public static void main(String[] args){HeapSort sort=new HeapSort();Node n1=sort.new Node(60);Node n2=sort.new Node(50);Node n3=sort.new Node(80);Node n4=sort.new Node(20);Node n5=sort.new Node(55);Node n6=sort.new Node(62);Node n7=sort.new Node(90);sort.insert(n1);sort.insert(n2);sort.insert(n3);sort.insert(n4);sort.insert(n5);sort.insert(n6);sort.insert(n7);sort.find(55);sort.display(n1);}}


java實現二叉排序樹

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.