題目
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"]
答案
class Solution {
public List<String> binaryTreePaths(TreeNode root) {
List<String> list = new ArrayList<String>();
if(root == null) return list;
binaryTreePaths(root, list, "");
return list;
}
public void binaryTreePaths(TreeNode root, List<String> list, String curr) {
if(root.left == null && root.right == null) {
curr = curr + Integer.toString(root.val);
list.add(curr);
return;
}
curr = curr + Integer.toString(root.val);
if(root.left != null)
binaryTreePaths(root.left, list, curr + "->");
if(root.right != null)
binaryTreePaths(root.right, list, curr + "->");
}
}