哈希表与二叉树

总览

微信图片_20200709173502.png

实现二叉树及其遍历方式

public class BinarayTree {
    public Node root;
    class Node{
        public T data;
        public Node leftChild;
        public Node rightChild;

        public Node(T data,Node leftChild,Node rightChild){
            this.data = data;
            this.leftChild = leftChild;
            this.rightChild = rightChild;
        }
    }

    public BinarayTree(String data){
        this.root = new Node<>(data,null,null);
    }

    public void createBinarayTree(){
        Node nodeB=new Node("B",null,null);
        Node nodeC=new Node("C",null,null);
        Node nodeD=new Node("D",null,null);
        Node nodeE=new Node("E",null,null);
        Node nodeF=new Node("F",null,null);
        Node nodeG=new Node("G",null,null);
        Node nodeH=new Node("H",null,null);
        Node nodeJ=new Node("J",null,null);
        Node nodeI=new Node("I",null,null);
        root.leftChild=nodeB;
        root.rightChild=nodeC;
        nodeB.leftChild=nodeD;
        nodeC.leftChild=nodeE;
        nodeC.rightChild=nodeF;
        nodeD.leftChild=nodeG;
        nodeD.rightChild=nodeH;
        nodeE.rightChild=nodeJ;
        nodeH.leftChild=nodeI;
    }

    /**
     * 中序访问树的所有节点
     */
    public void midOrderTraverse(Node root){//逻辑
        if (root == null) {
            return;
        }
        midOrderTraverse(root.leftChild);
        System.out.println("midOrderTraverse = "+root.data);
        midOrderTraverse(root.rightChild);
    }
    /**
     * 前序访问树的所有节点  Arrays.sort();
     */
    public void preOrderTraverse(Node root){
        if(root==null){
            return;
        }
        System.out.println("pre:"+root.data);
        preOrderTraverse(root.leftChild);
        preOrderTraverse(root.rightChild);
    }
    /**
     * 后序访问树的所有节点
     */
    public void postOrderTraverse(Node root){
        if(root==null){
            return;
        }
        postOrderTraverse(root.leftChild);
        postOrderTraverse(root.rightChild);
        System.out.println("post:"+root.data);
    }
}

你可能感兴趣的:(哈希表与二叉树)