java代碼實現二叉樹以及二叉樹遍歷

package mydata;
//二叉樹節點
public class BinaryTreeNode {
    private int data;
    private BinaryTreeNode leftChirld;
    private BinaryTreeNode rightChirld;

    public BinaryTreeNode(){}


    public int getData() {
        return data;
    }

    public void setData(int data) {
        this.data = data;
    }

    public BinaryTreeNode getLeftChirld() {
        return leftChirld;
    }

    public void setLeftChirld(BinaryTreeNode leftChirld) {
        this.leftChirld = leftChirld;
    }

    public BinaryTreeNode getRightChirld() {
        return rightChirld;
    }

    public void setRightChirld(BinaryTreeNode rightChirld) {
        this.rightChirld = rightChirld;
    }
}
//二叉樹部分功能實現部分

public class BinaryTree {
    private BinaryTreeNode root;
    public BinaryTree(){}
    public BinaryTree(BinaryTreeNode root){
        this.root=root;
    }

    public BinaryTreeNode getRoot() {
        return root;
    }

    public void setRoot(BinaryTreeNode root) {
        this.root = root;
    }
    public void insertLeft(BinaryTreeNode parent,int data){
        BinaryTreeNode newnode =new BinaryTreeNode();
        newnode.setData(data);
        parent.setLeftChirld(newnode);
    }
    public void insertRight(BinaryTreeNode parent,int data){
        BinaryTreeNode newnode =new BinaryTreeNode();
        newnode.setData(data);
        parent.setRightChirld(newnode);
    }
    public void order(BinaryTreeNode node){
        if(node!=null){
            order(node.getLeftChirld());
            System.out.println(node.getData());
            order(node.getRightChirld());
        }
    }
    public static void main(String[] args) {
        BinaryTreeNode root =new BinaryTreeNode();
        root.setData(20);
        BinaryTree tree=new BinaryTree(root);
        tree.insertLeft(root,10);
        tree.insertRight(root,30);
        tree.insertLeft(root.getLeftChirld(),1);
        tree.insertRight(root.getLeftChirld(),100);
        tree.order(root);
    }

}
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章