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"]
public List<String> binaryTreePaths(TreeNode root) {
List<String> res = new ArrayList<String>();
if(root!=null)
helper(root, Integer.toString(root.val), res);
return res;
}
public void helper(TreeNode root, String path, List res){
if(root.left==null&&root.right==null){
res.add(path);
}
if(root.left!=null){
helper(root.left, path + "->" + root.left.val, res);
}
if(root.right!=null){
helper(root.right, path + "->" + root.right.val, res);
}
}
转载请注明原文地址: https://ju.6miu.com/read-671358.html