排序二叉樹的描述也是一個遞迴的描述, 所以排序二叉樹的構造自然也用遞迴的:
排序二叉樹的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