二叉树中序遍历java代码实现

package binarytreesort;

public class BinaryTree {
    private int value;
    private BinaryTree leftNode;
    private BinaryTree rightNode;
    
    public BinaryTree() {
        // TODO Auto-generated constructor stub
    }
    
    public BinaryTree(int value,BinaryTree leftNode,BinaryTree rightNode) {
        this.value = value;
        this.leftNode = leftNode;
        this.rightNode = rightNode;
    }

    public int getValue() {
        return value;
    }

    public void setValue(int value) {
        this.value = value;
    }

    public BinaryTree getLeftNode() {
        return leftNode;
    }

    public void setLeftNode(BinaryTree leftNode) {
        this.leftNode = leftNode;
    }

    public BinaryTree getRightNode() {
        return rightNode;
    }

    public void setRightNode(BinaryTree rightNode) {
        this.rightNode = rightNode;
    }
        
}
/**
 * 
 */
package binarytreesort;

/**
 * @author Administrator
 * 
 */
public class BinaryTreeSort {

    /**
     * @param args
     */
    public static void main(String[] args) {
        BinaryTree binaryTree = new BinaryTree(10, new BinaryTree(8,
                new BinaryTree(5, new BinaryTree(2, null, null),
                        new BinaryTree(6, null, null)), new BinaryTree(9, null,
                        null)), new BinaryTree(15, null, null));
        preOderTraversal(binaryTree," ");
        System.out.println("\n");
        inOrderTraversal(binaryTree);
    }

    public static void inOrderTraversal(BinaryTree binaryTree){
            if(binaryTree.getLeftNode()!=null){
                inOrderTraversal(binaryTree.getLeftNode());
            }
            System.out.println(binaryTree.getValue());
            if(binaryTree.getRightNode()!=null){
                inOrderTraversal(binaryTree.getRightNode());
            }

        }
    
    public static void preOderTraversal(BinaryTree binaryTree,String blankSpace){
        System.out.println(blankSpace+binaryTree.getValue());
        blankSpace +=" "+blankSpace;
        if(binaryTree.getLeftNode()!=null){
            preOderTraversal(binaryTree.getLeftNode(),blankSpace);
        }
        if (binaryTree.getRightNode()!=null){
            preOderTraversal(binaryTree.getRightNode(),blankSpace);
        }
    }
}

 

posted @ 2013-05-26 11:05  唾手可得的树  阅读(614)  评论(0编辑  收藏  举报