题目描述
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"]
Credits:
Special thanks to @jianchao.li.fighter for adding this problem and creating all test cases.
分析
递归求解
代码
List<String> rt = new ArrayList<String>();
List<Integer> path = new ArrayList<Integer>();
public List<String> binaryTreePaths(TreeNode root) {
findPath(root);
return rt;
}
void findPath(TreeNode root) {
if (root == null) {
return;
}
path.add(root.val);
// 是一条路径,将path添加到rt中
if (root.left == null && root.right == null) {
StringBuffer sb = new StringBuffer();
sb.append(path.get(0));
for (int i = 1; i < path.size(); i++) {
sb.append("->" + path.get(i));
}
rt.add(sb.toString());
}
findPath(root.left);
findPath(root.right);
path.remove(path.size() - 1);
}