Leetcode(144) Binary Tree Preorder Traversal

Description:

Given a binary tree, return the preorder traversal of its nodes’ values.

解法:

递归解题,具体代码如下:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16

class Solution {
public List<Integer> preorderTraversal(TreeNode root) {
List<Integer> output = new ArrayList();
helper(root,output);
return output;
}
void helper(TreeNode root,List<Integer> output){
if(root == null){
return;
}
output.add(root.val);
helper(root.left,output);
helper(root.right,output);
}
}