题解 | #实现二叉树先序,中序和后序遍历#
实现二叉树先序,中序和后序遍历
http://www.nowcoder.com/practice/a9fec6c46a684ad5a3abd4e365a9d362
java实现,写简单点
public class Solution { /** * * @param root TreeNode类 the root of binary tree * @return int整型二维数组 */ private List<Integer> list = new ArrayList<>(); public int[][] threeOrders (TreeNode root) { // write code here int [][] arr = new int[3][]; for (int i = 0; i < 3; i++) { list.clear(); orders(root,i + 1); arr[i] = new int[list.size()]; for (int j = 0; j < list.size(); j++) { arr[i][j] = list.get(j); } } return arr; } public void orders(TreeNode root,int type) { if (root == null) return; if (type == 1) list.add(root.val); orders(root.left,type); if (type == 2) list.add(root.val); orders(root.right,type); if (type == 3) list.add(root.val); } }