Star

Leetcode 257. Binary Tree Path

Question

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

For example, given the following binary tree:

1
2
3
4
5
1
/ \
2 3
\
5

All root-to-leaf paths are:

1
["1->2->5", "1->3"]

Explanation

分治法,只用考虑左右子树会出现的情况就好了。另外此处注意叶子节点,就不用加“->”了。

Code

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
public class Solution {
public List<String> binaryTreePaths(TreeNode root) {
List<String> result = new ArrayList<>();
if (root == null) return result;
if (root.left == null && root.right == null) result.add(Integer.toString(root.val));
List<String> left = binaryTreePaths(root.left);
List<String> right = binaryTreePaths(root.right);
for(String s:left) {
result.add(root.val+"->"+s);
}
for(String s: right) {
result.add(root.val + "->" + s);
}
return result;
}
}