Given a binary tree, return all root-to-leaf paths.
Note: A leaf is a node with no children.
Example:
Input: 1 / \ 2 3 \ 5 Output: ["1->2->5", "1->3"] Explanation: All root-to-leaf paths are: 1->2->5, 1->3
backtracking, 记得返回上层的时候删掉该层节点
time: O(n) -- visited each node exactly once, space: O(logn) -- worst case: O(n) unbalanced tree
/** * Definition for a binary tree node. * public class TreeNode { * int val; * TreeNode left; * TreeNode right; * TreeNode(int x) { val = x; } * } */ class Solution { public List<String> binaryTreePaths(TreeNode root) { List<String> res = new ArrayList<>(); if(root == null) { return res; } dfs(root, new StringBuilder(), res); return res; } public void dfs(TreeNode root, StringBuilder sb, List<String> res) { if(root == null) { return; } int len = sb.length(); sb.append(root.val); if(root.left == null && root.right == null) { res.add(sb.toString()); sb.delete(len, sb.length()); return; } sb.append("->"); dfs(root.left, sb, res); dfs(root.right, sb, res); sb.delete(len, sb.length()); } }