p144

LeetCode 144 Binary Tree Preorder Traversal 题解

1.题目:

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].

题意:

输入一个二叉树,输出他的前序遍历节点的值。

2.解题思路:

dp

3.代码


[title] [] [url] [link text]
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
 

public class Solution {
public static void dp(TreeNode root, List<Integer> list) {

list.add(root.val);
if (root.left != null) {
dp(root.left, list);
}
if (root.right != null) {
dp(root.right, list);
}

return;
}

public static List<Integer> preorderTraversal(TreeNode root) {
List<Integer> list = new ArrayList<Integer>();
if (root == null)
return list;
dp(root, list);

//for (int i : list) {
// System.out.println(i);
//}
return list;

}

}


4.一些总结: