【牛客题霸-算法篇】实现二叉树先序,中序和后序遍历

PS:上篇回顾
题目描述

分别按照二叉树先序,中序和后序打印所有的节点。

示例1

输入

{1,2,3}

返回值

[[1,2,3],[2,1,3],[2,3,1]]

备注:

n≤10^6

题解代码如下

import java.util.*;

/*
 * 题目提供的节点的数据结构.
 * public class TreeNode {
 *   int val = 0;
 *   TreeNode left = null;
 *   TreeNode right = null;
 * }
 */

public class Solution {

    //存储先序遍历返回结果
    private List<Integer> first = new ArrayList<>();
    //存储中序遍历返回结果
    private List<Integer> in = new ArrayList<>();
    //存储后序遍历返回结果
    private List<Integer> out = new ArrayList<>();

    /**
     * @param root TreeNode类 the root of binary tree
     * @return int整型二维数组
     */
    public int[][] threeOrders(TreeNode root) {
        // write code here
        findFirst(root);
        findIn(root);
        findOut(root);
        //初始化结果返回
        int[][] result = new int[3][first.size()];
        //转换结果为 int[][] 的结构
        result[0] = first.stream().mapToInt(Integer::intValue).toArray();
        result[1] = in.stream().mapToInt(Integer::intValue).toArray();
        result[2] = out.stream().mapToInt(Integer::intValue).toArray();
        return result;
    }

    /**
     * 先序遍历.
     *
     * @param root
     */
    public void findFirst(TreeNode root) {
        if (root == null) return;
        first.add(root.val);
        findFirst(root.left);
        findFirst(root.right);

    }

    /**
     * 中序遍历.
     *
     * @param root
     */
    public void findIn(TreeNode root) {
        if (root == null) return;
        findIn(root.left);
        in.add(root.val);
        findIn(root.right);

    }

    /**
     * 后序遍历.
     *
     * @param root
     */
    public void findOut(TreeNode root) {
        if (root == null) return;
        findOut(root.left);
        findOut(root.right);
        out.add(root.val);
    }
}
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 3
    评论
评论 3
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

林志鹏JAVA

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值