二叉树的先序遍历,直接贴代码
/**
* Definition for binary tree
* public class TreeNode {
* int val;
* TreeNode left;
* TreeNode right;
* TreeNode(int x) { val = x; }
* }
*/
public class Solution {
public ArrayList<Integer> preorderTraversal (TreeNode root) {
ArrayList<Integer> list = new ArrayList<>();
post(list, root);
return list;
}
public static void post(ArrayList<Integer> list, TreeNode root) {
if (root != null) {
list.add(root.val);
post(list, root.left);
post(list, root.right);
}
}
}