257 Binary Tree Paths

r囧r小猫 2022-08-04 05:26 255阅读 0赞
  1. /** * Definition for a binary tree node. * public class TreeNode { * int val; * TreeNode left; * TreeNode right; * TreeNode(int x) { val = x; } * } */
  2. public class Solution {
  3. public List<String> binaryTreePaths(TreeNode root) {
  4. List<String> str = new ArrayList<String>();
  5. if (root == null)
  6. return str;
  7. PathsDFS(root, "", str);
  8. return str;
  9. }
  10. public static void PathsDFS(TreeNode root, String s, List<String> str) {
  11. if (root.left == null && root.right == null) {
  12. s += root.val;
  13. str.add(s);
  14. }
  15. if (root.left != null)
  16. PathsDFS(root.left, s + root.val + "->", str);
  17. if (root.right != null)
  18. PathsDFS(root.right, s + root.val + "->", str);
  19. }
  20. }

发表评论

表情:
评论列表 (有 0 条评论,255人围观)

还没有评论,来说两句吧...

相关阅读