题解 | #二叉树的前序遍历#
二叉树的前序遍历
http://www.nowcoder.com/practice/5e2135f4d2b14eb8a5b06fab4c938635
先序遍历:根左右
递归(通俗易懂)
List<Integer> list = new LinkedList<>();
public int[] preorderTraversal(TreeNode root) {
traverse2(root);
int[] res = new int[list.size()];
for(int i = 0; i < list.size(); i++)
res[i] = list.get(i);
return res;
// return list.stream().mapToInt(Integer::intValue).toArray(); // 采用java8的stream()
}
void traverse2(TreeNode root) {
if (root == null) return;
list.add(root.val);
traverse2(root.left);
traverse2(root.right);
}