给定一个二叉树,返回所有从根节点到叶子节点的路径。
说明: 叶子节点是指没有子节点的节点。
示例:
输入: 1 / \ 2 3 \ 5 输出: ["1->2->5", "1->3"] 解释: 所有根节点到叶子节点的路径为: 1->2->5, 1->3
解题思路:
递归解决,当我们遇到叶结点的时候,即没有左右子结点,那么此时一条完整的路径已经形成了,我们加上当前的叶结点后存入结果res中。
public static List<String> binaryTreePaths(TreeNode root) {
List<String> res = new ArrayList<>();
if(root!=null)
help(root,"",res);
return res;
}
private static void help(TreeNode root, String string, List<String> res) {
// TODO Auto-generated method stub
if(root.left==null&&root.right==null)
res.add(string.toString()+root.val);
if(root.left!=null)
help(root.left, string+root.val+"->", res);
if(root.right!=null)
help(root.right, string+root.val+"->", res);
}