二叉树的前序、中序、后序遍历指的是对于根节点的顺序
采用递归的方式解决,两个判断左右非null的语句+读取当前节点的语句
import java.util.*; /* * public class TreeNode { * int val = 0; * TreeNode left = null; * TreeNode right = null; * } */ public class Solution { /** * * @param root TreeNode类 the root of binary tree * @return int整型二维数组 */ List<Integer> list = new ArrayList<Integer>(); public int[][] threeOrders (TreeNode root) { // write code here preOlder(root); int len = list.size(); int[][] nums = new int[3][len]; int i=0; for(int n:list){ nums[0][i] = n; i++; } list.clear(); i=0; midOlder(root); for(int n:list){ nums[1][i] = n; i++; } list.clear(); i=0; postOlder(root); for(int n:list){ nums[2][i] = n; i++; } list.clear(); i=0; return nums; } public void preOlder(TreeNode root){ list.add(root.val); if(root.left!=null) preOlder(root.left); if(root.right!=null) preOlder(root.right); } public void midOlder(TreeNode root){ if(root.left!=null) midOlder(root.left); list.add(root.val); if(root.right!=null) midOlder(root.right); } public void postOlder(TreeNode root){ if(root.left!=null) postOlder(root.left); if(root.right!=null) postOlder(root.right); list.add(root.val); } }