题目

:::info 给你一个二叉树的根节点 root ,按 任意顺序 ,返回所有从根节点到叶子节点的路径。
叶子节点 是指没有子节点的节点。

示例 1:
输入:root = [1,2,3,null,5]
输出:[“1->2->5”,”1->3”]

示例 2:
输入:root = [1]
输出:[“1”]

来源:力扣(LeetCode)
链接:https://leetcode.cn/problems/binary-tree-paths
著作权归领扣网络所有。商业转载请联系官方授权,非商业转载请注明出处。 ::: image.png

代码

  1. /**
  2. * Definition for a binary tree node.
  3. * public class TreeNode {
  4. * int val;
  5. * TreeNode left;
  6. * TreeNode right;
  7. * TreeNode() {}
  8. * TreeNode(int val) { this.val = val; }
  9. * TreeNode(int val, TreeNode left, TreeNode right) {
  10. * this.val = val;
  11. * this.left = left;
  12. * this.right = right;
  13. * }
  14. * }
  15. */
  16. class Solution {
  17. public List<String> binaryTreePaths(TreeNode root) {
  18. List<String> paths = new ArrayList<String>();
  19. dfs(root,"",paths);
  20. return paths;
  21. }
  22. //path为当前正在遍历的路径,paths为最终的路径集合
  23. public static void dfs(TreeNode root,String path,List<String> paths){
  24. if(root != null){
  25. StringBuffer pathSB = new StringBuffer(path);
  26. pathSB.append(Integer.toString(root.val));
  27. if(root.left == null && root.right == null){ //节点为叶子节点
  28. paths.add(pathSB.toString()); //集合中存放的是字符串
  29. }else{ //节点为非叶子节点
  30. pathSB.append("->");
  31. dfs(root.left,pathSB.toString(),paths);
  32. dfs(root.right,pathSB.toString(),paths);
  33. }
  34. }
  35. }
  36. }