来源

来源:力扣(LeetCode)
链接:https://leetcode-cn.com/problems/binary-tree-paths/

描述

给定一个二叉树,返回所有从根节点到叶子节点的路径。
示例:
输入:
1
/ \
2 3
\
5
输出: [“1->2->5”, “1->3”]

题解

递归版

  1. class Solution {
  2. public List<String> binaryTreePaths(TreeNode root) {
  3. List<String> paths = new LinkedList<>();
  4. construct_paths(root, "", paths);
  5. return paths;
  6. }
  7. public void construct_paths(TreeNode root, String path, List<String> paths) {
  8. if (null != root) {
  9. path += Integer.toString(root.val);
  10. if (root.left == null && root.right == null) {
  11. paths.add(path);
  12. } else {
  13. path += "->";
  14. construct_paths(root.left, path, paths);
  15. construct_paths(root.right, path, paths);
  16. }
  17. }
  18. }
  19. }

复杂度分析

  • 时间复杂度:每个节点只会被访问一次,因此时间复杂度为257. 二叉树的所有路径(Binary Tree Paths) - 图1,其中257. 二叉树的所有路径(Binary Tree Paths) - 图2表示节点数目;
  • 空间复杂度:257. 二叉树的所有路径(Binary Tree Paths) - 图3。在最坏情况下,当二叉树中每个节点只有一个孩子节点时,递归的层数为257. 二叉树的所有路径(Binary Tree Paths) - 图4,此时空间复杂度为257. 二叉树的所有路径(Binary Tree Paths) - 图5。在最好情况下,当二叉树为平衡二叉树时,它的高度为257. 二叉树的所有路径(Binary Tree Paths) - 图6,此时空间复杂度为 257. 二叉树的所有路径(Binary Tree Paths) - 图7