PS:上篇回顾
- 上篇博文写了一棵二叉树的构造和其深度优先遍历算法(地址:Java实现构造一棵二叉树及其深度优先算法)。
- 下面来写一道题练习一下。这道题是【牛客题霸-算法篇】的一道面试常考题,题目地址:点击跳转题目地址
- 具体题目如下
题目描述
分别按照二叉树先序,中序和后序打印所有的节点。
示例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);
}
}