p257

LeetCode p257 Binary Tree Paths 题解

1.题目:

Given a binary tree, return all root-to-leaf paths.

For example, given the following binary tree:

1
/ \
2 3
\
5

All root-to-leaf paths are:

[“1->2->5”, “1->3”]

题意:

输出一个二叉树包含的所有的路径。

2.解题思路:

见代码

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
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
 
/**
* 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<String> ans = new ArrayList<String>();

public List<String> binaryTreePaths(TreeNode root) {
List<Integer> list = new ArrayList<Integer>();
binaryTreePaths(root, list);
return ans;
}

public void binaryTreePaths(TreeNode root, List<Integer> list) {
if (root == null)
return;
if (root.left == null && root.right == null) {
list.add(root.val);
int len = list.size();
StringBuilder builder = new StringBuilder();
for (int i = 0; i < len - 1; i++) {
builder.append(list.get(i) + "->");
}
builder.append(list.get(len - 1));
// System.out.println(sb.toString());
ans.add(builder.toString());
// sb.deleteCharAt(sb.length() - 1);
return;
}
list.add(root.val);
if (root.left != null) {
binaryTreePaths(root.left, list);
list.remove(list.size() - 1);
}

if (root.right != null) {
binaryTreePaths(root.right, list);
list.remove(list.size() - 1);
}

}
}

4.一些总结: