Easy
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”]
5ms:
public List<String> binaryTreePaths(TreeNode root) {
List<String> result = new ArrayList<String>();
if(root==null) return result;
List<Integer> list = new LinkedList<Integer>();
dfs(result,list,root);
return result;
}
private void dfs(List<String> result,List<Integer> list,TreeNode node){
list.add(node.val);
if(node.left==null&&node.right==null){
StringBuffer sb = new StringBuffer();
for(Integer i:list){
sb.append(i);
sb.append("->");
}
result.add(sb.substring(0,sb.length()-2));
}
if(node.left!=null)
dfs(result,list,node.left);
if(node.right!=null)
dfs(result,list,node.right);
list.remove(list.size()-1);
}
2ms:
public List<String> binaryTreePaths(TreeNode root) {
if(root == null) return new ArrayList<String>();
List<String> result = new ArrayList<String>();
dfs(root, "", result);
return result;
}
private void dfs(TreeNode root, String s, List<String> result){
if(root.left == null && root.right==null)
result.add(s+String.valueOf(root.val));
if(root.left != null)
dfs(root.left, s+String.valueOf(root.val)+"->", result);
if(root.right !=null)
dfs(root.right, s+String.valueOf(root.val)+"->", result);
}