leetcode二叉树相关模板

package com.leetcode102;

import java.util.List;

public class Main {
    public static void main(String[] args) {
        Integer[] arr = {3, 9, 20, null, null, 15, 7};
        TreeNode tree = createTree(arr, 0);
        printPreOrder(tree);
        System.out.println();
        printMidOrder(tree);
        System.out.println();
        printAfterOrder(tree);
        System.out.println();
    }

    /**
     * 前序遍历
     */
    public static void printPreOrder(TreeNode tree) {
        if (tree != null) {
            System.out.print(tree.val == null ? "" : tree.val + " ");
            printPreOrder(tree.left);
            printPreOrder(tree.right);
        }
    }

    /**
     * 中序遍历
     */
    public static void printMidOrder(TreeNode tree) {
        if (tree != null) {
            printMidOrder(tree.left);
            System.out.print(tree.val == null ? "" : tree.val + " ");
            printMidOrder(tree.right);
        }
    }

    /**
     * 后序遍历
     */
    public static void printAfterOrder(TreeNode tree) {
        if (tree != null) {
            printAfterOrder(tree.left);
            printAfterOrder(tree.right);
            System.out.print(tree.val == null ? "" : tree.val + " ");
        }
    }

    /**
     * 创建一个二叉树
     * ----3
     * -9     20
     * -----15  17
     */
    public static TreeNode createTree(Integer[] arr, int index) {

        TreeNode root = null;
        if (index < arr.length) {
            root = new TreeNode(arr[index]);
            root.left = createTree(arr, 2 * index + 1);
            root.right = createTree(arr, 2 * index + 2);
        }

        return root;
    }
}

class TreeNode {
    Integer val;
    TreeNode left;
    TreeNode right;

    TreeNode() {
    }

    TreeNode(Integer val) {
        this.val = val;
    }

    TreeNode(int val, TreeNode left, TreeNode right) {
        this.val = val;
        this.left = left;
        this.right = right;
    }
}

你可能感兴趣的:(算法与数据结构,leetcode,java,算法)