Given a binary tree, return all root-to-leaf paths.
Note: A leaf is a node with no children.
Example:
Input:1/ \2 3\5Output: ["1->2->5", "1->3"]Explanation: All root-to-leaf paths are: 1->2->5, 1->3
题意
打印一棵树从根结点到叶结点的所有路径。
思路
简单的DFS处理即可。
代码实现
class Solution {public List<String> binaryTreePaths(TreeNode root) {List<String> ans = new ArrayList<>();if (root != null) {dfs(root, ans, "");}return ans;}private void dfs(TreeNode x, List<String> ans, String s) {s += s.equals("") ? x.val : "->" + x.val;if (x.left != null) {dfs(x.left, ans, s);}if (x.right != null) {dfs(x.right, ans, s);}if (x.left == null && x.right == null) {ans.add(s);}}}
