有關類別 BinaryTree 中的 inorderDisplay() 函數, 請參考這裡.
- BTreeInLS.java :
- package DSwJ.S16;
- public class BTreeInLS
extends Comparablesuper T>> { - private TNode
root = null;- private int level=0;
- public BTreeInLS(){}
- public void addNode(T item){
- TNode
tmpNode = root; - int tmpLevel = level;
- if(tmpNode==null) {
- root = new TNode
(item); - root.right = null;
- root.left = null;
- } else {
- //TNode
prevNode = null; - while(true) {
- if(item.compareTo(tmpNode.nodeValue)>0) { // 往右子樹移動
- if(tmpNode.right==null) {
- if(level
1){level++;} - tmpNode.right = new TNode
(item); - tmpNode.right.left = null;
- tmpNode.right.right = null;
- return;
- } else {
- tmpNode = tmpNode.right;
- tmpLevel++;
- }
- //prevNode = tmpNode;
- } else { // 往左子樹移動
- if(tmpNode.left==null) {
- if(level
1){level++;} - tmpNode.left = new TNode
(item); - tmpNode.left.left = null;
- tmpNode.left.right = null;
- return;
- } else {
- tmpNode = tmpNode.left;
- tmpLevel++;
- }
- //prevNode = tmpNode;
- }
- }
- }
- }
- public int getLevel(){return level;}
- public void showData(){
- for(int i=0; i<=level; i++) {
- showNode(i, 0, root);
- }
- System.out.println();
- }
- public TNode
getRoot(){ return root;}- public void showNode(int tlvl, int clvl, TNode
node) { - if(node!=null) {
- if(tlvl == clvl) {
- System.out.printf("[%s] ", node.nodeValue);
- } else {
- showNode(tlvl, clvl+1, node.left);
- showNode(tlvl, clvl+1, node.right);
- }
- }
- }
- public static void main(String args[]) {
- int data[] = {0,6,3,5,9,7,8,4,2}; // 原始陣列
- BTreeInLS
bTreeLS = new BTreeInLS (); - for(int i=0; i
- bTreeLS.addNode(data[i]);
- }
- System.out.print("Source Data: ");
- bTreeLS.showData();
- System.out.println("Inorder > "+BinaryTree.inorderDisplay(bTreeLS.getRoot()));
- }
- }
執行結果 :
Source Data: [0] [6] [3] [9] [2] [5] [7] [4] [8]
Inorder > 0 2 3 4 5 6 7 8 9
沒有留言:
張貼留言