题解 | #实现二叉树先序,中序和后序遍历#
实现二叉树先序,中序和后序遍历
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 int[][] a = new int[3][3]; for (int i = 0; i < 3; i++) { int[] b = {}; if (root == null) { a[i] = b; continue; } List<Integer> list = new ArrayList(); if (i == 0) { list = xian(root); } else if (i == 1) { list = zhon(root); } else { list = hou(root); } b = list.stream().mapToInt(Integer::valueOf).toArray(); a[i]=b; } return a; } public List<Integer> xian(TreeNode root) { List<Integer> a = new ArrayList(); if (root != null) { a.add(root.val); a.addAll(xian(root.left)); a.addAll(xian(root.right)); } return a; } public List<Integer> zhon(TreeNode root) { List<Integer> a = new ArrayList(); if (root != null) { a.addAll(zhon(root.left)); a.add(root.val); a.addAll(zhon(root.right)); } return a; } public List<Integer> hou(TreeNode root) { List<Integer> a = new ArrayList(); if (root != null) { a.addAll(hou(root.left)); a.addAll(hou(root.right)); a.add(root.val); } return a; } }
先序就是中左右,
中序就是左中右,
后序就是左右中,
记死就行。