二叉树(Java)

本文最后更新于:6 个月前

package TreeNode;

/**
 * @author QiuQian
 * 二叉树
 */
public class TreeNode {
    char val;
    TreeNode left;
    TreeNode right;

    public TreeNode(char val) {
        this.val = val;
        this.left = null;
        this.right = null;
    }
}


package TreeNode;

/**
 * @author QiuQian
 * 三中递归遍历方式
 */
public class Traverse {

    /**
     * 前序遍历
     * @param root
     */
    public void preOrder(TreeNode root) {
        if( root == null ) {
            return;
        }
        System.out.print(root.val + "->");
        preOrder(root.left);
        preOrder(root.right);
    }

    /**
     * 后序遍历
     * @param root
     */
    public void postOrder(TreeNode root) {
        if( root == null ) {
            return;
        }
        postOrder(root.left);
        postOrder(root.right);
        System.out.print(root.val + "->");
    }

    /**
     * 中序遍历
     * @param root
     */
    public void inOrder(TreeNode root) {
        if( root == null ) {
            return;
        }
        inOrder(root.left);
        System.out.print(root.val + "->");
        inOrder(root.right);
    }
}


package TreeNode;

/**
 * @author QiuQian
 * LeetCode 刷题用
 */
public class Main {
    public static void main(String[] args) {
        // 构建二叉树
        TreeNode nodeA = new TreeNode('A');
        TreeNode nodeB = new TreeNode('B');
        TreeNode nodeC = new TreeNode('C');
        TreeNode nodeD = new TreeNode('D');
        TreeNode nodeE = new TreeNode('E');
        TreeNode nodeF = new TreeNode('F');
        TreeNode nodeG = new TreeNode('G');
        TreeNode nodeH = new TreeNode('H');
        TreeNode nodeI = new TreeNode('I');

        nodeA.left = nodeB;
        nodeB.left = nodeD;
        nodeB.right = nodeF;
        nodeF.left = nodeE;
        nodeA.right = nodeC;
        nodeC.left = nodeG;
        nodeG.right = nodeH;
        nodeC.right = nodeI;

        Traverse pre = new Traverse();

        // 前序遍历
        System.out.println("前序遍历");
        pre.preOrder(nodeA);
        System.out.println();
        // 中序遍历
        System.out.println("中序遍历");
        pre.inOrder(nodeA);
        System.out.println();
        // 后续遍历
        System.out.println("后序遍历");
        pre.postOrder(nodeA);
        System.out.println();

    }
}

image-20210522161600368