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 class Solution { public List<String> binaryTreePaths(TreeNode root) { List<String> res = new ArrayList<String>(); if (root == null) { return res; } String str = root.val +""; helper(res, root, str); return res; } public void helper(List<String> res, TreeNode root, String str) { if (root.left == null && root.right == null) { res.add(str); return; } if (root.left != null) { helper(res, root.left, str + "->" + root.left.val); } if (root.right != null) { helper(res, root.right, str +"->" + root.right.val); } } }
没有评论:
发表评论