1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20
| class Solution { List<Integer> ans = new ArrayList<>(); public List<Integer> preorderTraversal(TreeNode root) { dfs(root); return ans; }
public void dfs(TreeNode root){ if(root == null){ return; } ans.add(root.val); if(root.left != null){ dfs(root.left); } if(root.right != null){ dfs(root.right); } } }
|