点评:这题恶心人的一点,如果传入的节点不存在,必须返回一个长度为0的空数组,而不能返回null
- 首先判断是否为null,为空返回空数组
- 递归遍历取值存放在list中
- 从list中取值,组装答案返回
import java.util.*;
public class Solution {
/**
* 代码中的类名、方法名、参数名已经指定,请勿修改,直接返回方法规定的值即可
*
*
* @param root TreeNode类
* @return int整型一维数组
*/
public int[] preorderTraversal (TreeNode root) {
//1为空情况
if(root == null){
int[] res1 = new int[0];
return res1;
}
//2 取值
List<Integer> list = new ArrayList();
recursionOrder(root,list);
//3 组装
int[] res = new int[list.size()];
for(int i =0;i<list.size();i++){
res[i] = list.get(i);
}
return res;
}
//递归 取值
public static void recursionOrder(TreeNode root,List<Integer> list){
if(root == null){
return ;
}
list.add(root.val);
recursionOrder(root.left,list);
recursionOrder(root.right,list);
}
}