题解 | #实现二叉树先序,中序和后序遍历#相对简单
实现二叉树先序,中序和后序遍历
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整型二维数组 */ ArrayList<Integer> pre = new ArrayList<Integer>(); ArrayList<Integer> post = new ArrayList<Integer>(); ArrayList<Integer> mid = new ArrayList<Integer>(); public int[][] threeOrders (TreeNode root) { int[][] res = new int[3][]; preOrder(root); midOrder(root); postOrder(root); int[] pre2 = new int[pre.size()]; int[] post2 = new int[post.size()]; int[] mid2 = new int[mid.size()]; for(int i=0; i<pre.size(); i++){ pre2[i] = (int)pre.get(i); } for(int j=0; j<mid.size(); j++){ mid2[j] = (int)mid.get(j); } for(int k=0; k<post.size(); k++){ post2[k] = (int)post.get(k); } res[0] = pre2; res[1] = mid2; res[2] = post2; return res; } public void preOrder(TreeNode node){ if(node == null){ return; } pre.add(node.val); preOrder(node.left); preOrder(node.right); } public void midOrder(TreeNode node){ if(node == null){ return; } midOrder(node.left); mid.add(node.val); midOrder(node.right); } public void postOrder(TreeNode node){ if(node == null){ return; } postOrder(node.left); postOrder(node.right); post.add(node.val); } }