257.二叉树的所有路径
方法:深度优先搜索
/*** Definition for a binary tree node.* public class TreeNode {* int val;* TreeNode left;* TreeNode right;* TreeNode() {}* TreeNode(int val) { this.val = val; }* TreeNode(int val, TreeNode left, TreeNode right) {* this.val = val;* this.left = left;* this.right = right;* }* }*/
class Solution {public List<String> binaryTreePaths(TreeNode root) {List<String> ans = new ArrayList<>();StringBuilder sb = new StringBuilder();dfs(root,ans,sb);return ans;}public void dfs(TreeNode root,List<String> paths,StringBuilder s){if(root == null){return;} s.append(root.val);if(root.left == null && root.right == null){paths.add(s.toString());return;}dfs(root.left,paths,new StringBuilder(s).append("->"));dfs(root.right,paths,new StringBuilder(s).append("->"));}
}