题解 | 实现二叉树先序,中序和后序遍历
实现二叉树先序,中序和后序遍历
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) { // write code here List<List<Integer>> lists = new ArrayList<>(); for (int i = 0; i < 3; ++i) lists.add(new ArrayList<Integer>()); getPreOrder(root, lists.get(0)); getMidOrder(root, lists.get(1)); getBackOrder(root, lists.get(2)); int n = lists.get(0).size(); int [][] ans = new int[3][n]; for (int i = 0; i < 3; ++i) { for (int j = 0; j < n; ++j) { ans[i][j] = lists.get(i).get(j); } } return ans; } // 前序 List getPreOrder(TreeNode root, List list) { if (root == null) return null; list.add(root.val);//实际上不加泛型检查也可以 getPreOrder(root.left, list); getPreOrder(root.right, list); return list; } // 中序 List<Integer> getMidOrder(TreeNode root, List<Integer> list) { if (root == null) return null; getMidOrder(root.left, list); list.add(root.val); getMidOrder(root.right, list); return list; } // 后序 List<Integer> getBackOrder(TreeNode root, List<Integer> list) { if (root == null) return null; getBackOrder(root.left, list); getBackOrder(root.right, list); list.add(root.val); return list; } }