java二叉樹排序演算法

來源:互聯網
上載者:User

排序二叉樹的描述也是一個遞迴的描述, 所以排序二叉樹的構造自然也用遞迴的:

排序二叉樹的3個特徵:

1:當前node的所有左孩子的值都小於當前node的值;

2:當前node的所有右孩子的值都大於當前node的值;

3:孩子節點也滿足以上兩點

package test.sort;</p><p>public class BinaryNode {<br />/**<br />* author: sunxing007,<br />* 轉載請註明來自http://blog.csdn.net/sunxing007<br />**/<br />private int value;//current value<br />private BinaryNode lChild;//left child<br />private BinaryNode rChild;//right child</p><p>public BinaryNode(int value, BinaryNode l, BinaryNode r){<br />this.value = value;<br />this.lChild = l;<br />this.rChild = r;<br />}</p><p>public BinaryNode getLChild() {<br />return lChild;<br />}<br />public void setLChild(BinaryNode child) {<br />lChild = child;<br />}<br />public BinaryNode getRChild() {<br />return rChild;<br />}<br />public void setRChild(BinaryNode child) {<br />rChild = child;<br />}<br />public int getValue() {<br />return value;<br />}<br />public void setValue(int value) {<br />this.value = value;<br />}</p><p>//iterate all node.<br />public static void iterate(BinaryNode root){<br />if(root.lChild!=null){<br />iterate(root.getLChild());<br />}<br />System.out.print(root.getValue() + " ");<br />if(root.rChild!=null){<br />iterate(root.getRChild());<br />}<br />}</p><p>/**<br /> * add child to the current node to construct a tree.<br /> * Time: O( nlog(n) )<br /> * **/<br />public void addChild(int n){<br />if(n<value){<br />if(lChild!=null){<br />lChild.addChild(n);<br />}<br />else{<br />lChild = new BinaryNode(n, null, null);<br />}<br />}<br />else{<br />if(rChild!=null){<br />rChild.addChild(n);<br />}<br />else{<br />rChild = new BinaryNode(n, null, null);<br />}<br />}<br />}</p><p>//test case.<br />public static void main(String[] args){<br />System.out.println();<br />int[] arr = new int[]{23,54,1,65,9,3,100};<br />BinaryNode root = new BinaryNode(arr[0], null, null);<br />for(int i=1; i<arr.length; i++){<br />root.addChild(arr[i]);<br />}<br />BinaryNode.iterate(root);<br />}<br />}<br />

 

轉載請註明來自http://blog.csdn.net/sunxing007

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在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.