Given a binary tree, return the preorder traversal of its nodes' values.
For example:
Given binary tree {1,#,2,3}
,
1 \ 2 / 3
return [1,2,3]
.
Note: Recursive solution is trivial, could you do it iteratively?
思路:前序遍历。helper function用于想recursive但是method给的parameter不够。上课讲的东西有些还是蛮有用的。
/** * Definition for a binary tree node. * public class TreeNode { * int val; * TreeNode left; * TreeNode right; * TreeNode(int x) { val = x; } * } */ public class Solution { public List<Integer> preorderTraversal(TreeNode root) { List<Integer> res=new ArrayList<>(); if(root==null){ return res; } helper(res,root); return res; } public void helper(List<Integer> res,TreeNode root){ if(root==null){ return; } res.add(root.val); helper(res,root.left); helper(res,root.right); } }