java 二维List转二维数组
实现二叉树先序,中序和后序遍历
http://www.nowcoder.com/questionTerminal/a9fec6c46a684ad5a3abd4e365a9d362
import java.util.*;
public class Solution {
List<Integer> list = new ArrayList<>();
private List<List<Integer>> result = new ArrayList<>();
public int[][] threeOrders (TreeNode root) {
// 先遍历二叉树,并添加到 result 中
preOrder(root);
result.add(new ArrayList(list));
list.clear();
inOrder(root);
result.add(new ArrayList(list));
list.clear();
postOrder(root);
result.add(new ArrayList(list));
// 将二层 List 转为 二维数组
int[][] res = new int[result.size()][result.get(0).size()];
for(int i=0; i<result.size(); i++) {
res[i] = result.get(i).stream().mapToInt(Integer::valueOf).toArray();
}
return res;
}
// 后面三种二叉树的递归遍历
private void preOrder(TreeNode root) {
if(root==null) return;
list.add(root.val);
preOrder(root.left);
preOrder(root.right);
}
private void inOrder(TreeNode root) {
if(root==null) return;
inOrder(root.left);
list.add(root.val);
inOrder(root.right);
}
private void postOrder(TreeNode root) {
if(root==null) return;
postOrder(root.left);
postOrder(root.right);
list.add(root.val);
}}

查看18道真题和解析