题解 | #二叉树的前序遍历#
二叉树的前序遍历
http://www.nowcoder.com/practice/5e2135f4d2b14eb8a5b06fab4c938635
import java.util.*;
/*
* public class TreeNode {
* int val = 0;
* TreeNode left = null;
* TreeNode right = null;
* public TreeNode(int val) {
* this.val = val;
* }
* }
*/
public class Solution {
public int[] preorderTraversal (TreeNode root) {
List<Integer> list=new ArrayList<>();
dfs(list,root);
int[] res=new int[list.size()];
for (int i = 0; i < list.size(); i++) {
res[i]=list.get(i);
}
return res;
}
public void dfs(List<Integer> list,TreeNode root){
if(root!=null){
list.add(root.val);
dfs(list,root.left);
dfs(list,root.right);
}
}
}