题解 | #实现二叉树先序,中序和后序遍历#
实现二叉树先序,中序和后序遍历
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整型二维数组 */
//用遍历的方法实现先序,中序和后序遍历
static ArrayList<Integer> list1 = new ArrayList<Integer>();
static ArrayList<Integer> list2 = new ArrayList<Integer>();
static ArrayList<Integer> list3 = new ArrayList<Integer>();
public int[][] threeOrders (TreeNode root) {
// write code here
preOrder(root);
inOrder(root);
posOrder(root);
int[][] result = new int[3][list1.size()];
for(int j = 0; j < list1.size(); j++){
result[0][j] = list1.get(j);
result[1][j] = list2.get(j);
result[2][j] = list3.get(j);
}
return result;
}
public static void preOrder (TreeNode root){
if(root == null){
return;
}
list1.add(root.val);
preOrder(root.left);
preOrder(root.right);
}
public static void inOrder (TreeNode root){
if(root == null){
return;
}
inOrder(root.left);
list2.add(root.val);
inOrder(root.right);
}
public static void posOrder (TreeNode root){
if(root == null){
return;
}
posOrder(root.left);
posOrder(root.right);
list3.add(root.val);
}
}