题解 | #实现二叉树先序,中序和后序遍历#
实现二叉树先序,中序和后序遍历
https://www.nowcoder.com/practice/a9fec6c46a684ad5a3abd4e365a9d362
import java.util.*; /* * public class TreeNode { * int val = 0; * TreeNode left = null; * TreeNode right = null; * public TreeNode(int val) { * this.val = val; * } * } */ public class Solution { /** * 代码中的类名、方法名、参数名已经指定,请勿修改,直接返回方法规定的值即可 * * * @param root TreeNode类 the root of binary tree * @return int整型二维数组 */ public int[][] threeOrders (TreeNode root) { // 前序遍历 根节点-左-右 int a[][] = {Arrays.stream(diguiLeft(root, new ArrayList())).mapToInt(Integer::valueOf).toArray(),Arrays.stream(diguiMiddle(root, new ArrayList())).mapToInt(Integer::valueOf).toArray(), Arrays.stream(diguiRight(root, new ArrayList())).mapToInt(Integer::valueOf).toArray()}; // 中序遍历 左-根节点-右 return a; } public static Integer[] diguiLeft(TreeNode root, ArrayList<Integer> arry) { if (root != null) { arry.add(root.val); diguiLeft(root.left, arry); diguiLeft(root.right, arry); } return arry.toArray(new Integer[arry.size()]); } public static Integer[] diguiMiddle (TreeNode root, ArrayList<Integer> arry) { if (root != null) { diguiMiddle(root.left, arry); arry.add(root.val); diguiMiddle(root.right, arry); } return arry.toArray(new Integer[arry.size()]); } public static Integer[] diguiRight (TreeNode root, ArrayList<Integer> arry) { if (root != null) { diguiRight(root.left, arry); diguiRight(root.right, arry); arry.add(root.val); } return arry.toArray(new Integer[arry.size()]); } }