二叉树的递归遍历(java版)

1. 场景需求

二叉树如图


二叉树的递归遍历(java版)_第1张图片
普通二叉树

java中利用递归实现二叉树的各种遍历

  • 前序遍历
  • 中序遍历
  • 后序遍历

3.代码实现

@Accessors(chain = true)
@Data
public class TreeNode {
    int val;
    private TreeNode left;
    private TreeNode right;
    public TreeNode(int val) {
        this.val = val;
    }

    public final static List listFirst = new ArrayList<>();
    public final static List listSecond = new ArrayList<>();
    public final static List listLast = new ArrayList<>();
    
    public static void main(String[] args) {
        // 构造二叉树
        TreeNode root = new TreeNode(1);
        TreeNode n2 = new TreeNode(2);
        TreeNode n3 = new TreeNode(3);
        TreeNode n4 = new TreeNode(4);
        TreeNode n5 = new TreeNode(5);
        TreeNode n6 = new TreeNode(6);
        TreeNode n7 = new TreeNode(7);
        TreeNode n8 = new TreeNode(8);
        root.setLeft(n2).setRight(n3);
        n2.setLeft(n4);
        n4.setRight(n7);
        n3.setLeft(n5).setRight(n6);
        n6.setLeft(n8);

        // 遍历
        first(root);
        second(root);
        last(root);

        // 打印
        System.out.println("先序遍历:");
        listFirst.stream().forEach(System.out::print);
        System.out.println("");
        System.out.println("中序遍历:");
        listSecond.stream().forEach(System.out::print);
        System.out.println("");
        System.out.println("后序遍历:");
        listLast.stream().forEach(System.out::print);

    }

    // 先序遍历
    public static void first(TreeNode treeNode) {
        listFirst.add(treeNode.val);
        if (treeNode.left != null) {
            first(treeNode.left);
        }
        if (treeNode.right != null) {
            first(treeNode.right);
        }
    }

    // 中序遍历
    public static void second(TreeNode treeNode) {
        if (treeNode.left != null) {
            second(treeNode.left);
        }
        listSecond.add(treeNode.val);
        if (treeNode.right != null) {
            second(treeNode.right);
        }
    }

    // 后序遍历
    public static void last(TreeNode treeNode) {
        if (treeNode.left != null) {
            last(treeNode.left);
        }
        if (treeNode.right != null) {
            last(treeNode.right);
        }
        listLast.add(treeNode.val);
    }
}

3.测试结果

先序遍历:
12473568
中序遍历:
47215386
后序遍历:
74258631

你可能感兴趣的:(二叉树的递归遍历(java版))