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"]
/**
* Definition for a binary tree node.
* public class TreeNode {
* int val;
* TreeNode left;
* TreeNode right;
* TreeNode(int x) { val = x; }
* }
*/
public class Solution {
public List<String> binaryTreePaths(TreeNode root) {
List<String> res = new ArrayList<String>();
if (root == null) {
return res;
}
helper(root, new ArrayList<Integer>(), res);
return res;
}
private void helper(TreeNode node, List<Integer> curList, List<String> res) {
if (node.left == null && node.right == null) {
StringBuilder sb = new StringBuilder();
for (int i = 0; i < curList.size(); i++) {
sb.append(curList.get(i)).append("->");
}
sb.append(node.val);
res.add(sb.toString());
} else {
if (node.left != null) {
curList.add(node.val);
helper(node.left, curList, res);
curList.remove(curList.size() - 1);
}
if (node.right != null) {
curList.add(node.val);
helper(node.right, curList, res);
curList.remove(curList.size() - 1);
}
}
}
}
没有评论:
发表评论