题目描述:
递归
/** * Definition for a binary tree node. * public class TreeNode { * int val; * TreeNode left; * TreeNode right; * TreeNode() {} * TreeNode(int val) { this.val = val; } * TreeNode(int val, TreeNode left, TreeNode right) { * this.val = val; * this.left = left; * this.right = right; * } * } */ class Solution { public List<Integer> preorderTraversal(TreeNode root) { List<Integer> list=new ArrayList<Integer>(); recurse(root,list); return list; } public void recurse(TreeNode root,List<Integer> res){ //递归 if(root==null){ return ; } res.add(root.val); recurse(root.left,res); recurse(root.right,res); } }
写法: