题解 | #实现二叉树先序,中序和后序遍历#
实现二叉树先序,中序和后序遍历
http://www.nowcoder.com/practice/a9fec6c46a684ad5a3abd4e365a9d362
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整型二维数组 */ public int[][] threeOrders (TreeNode root) { // write code here int[][] arr = new int[3][]; List preList = new ArrayList(); List inList = new ArrayList(); List postList = new ArrayList(); myOrder(root, preList, inList, postList); arr[0] = listToArr(preList); arr[1] = listToArr(inList); arr[2] = listToArr(postList); return arr; } private static void myOrder(TreeNode root, List<Integer> listPre, List<Integer> listIn, List<Integer> listPost) { if(root != null){ listPre.add(root.val); myOrder(root.left, listPre, listIn, listPost); listIn.add(root.val); myOrder(root.right, listPre, listIn, listPost); listPost.add(root.val); } } private static int[] listToArr(List<Integer> list){ int[] arr = new int[list.size()]; for(int i = 0; i < list.size(); i++){ arr[i] = list.get(i); } return arr; } // private static void preOrder(TreeNode root, List<Integer> list){ // if(root != null){ // list.add(root.val); // preOrder(root.left, list); // preOrder(root.right, list); // } // } // private static void inOrder(TreeNode root, List<Integer> list){ // if(root != null){ // inOrder(root.left, list); // list.add(root.val); // inOrder(root.right, list); // } // } // private static void postOrder(TreeNode root, List<Integer> list){ // if(root != null){ // postOrder(root.left, list); // postOrder(root.right, list); // list.add(root.val); // } // } }