力扣257. 二叉树的所有路径(遍历思想解决)

Problem: 257. 二叉树的所有路径

文章目录

题目描述


思路

遍历思想(利用二叉树的先序遍历)

利用先序遍历的思想,我门用一个List变量path记录当前先序遍历的节点,当遍历到根节点时,将其添加到另一个List变量res中,当递归往回归的时候删除当前path中的最后一个值

复杂度

时间复杂度:

O ( n ) O(n) O(n);其中 n n n为二叉树的节点个数

空间复杂度:

O ( h ) O(h) O(h);其中 h h h为二叉树的高度

Code

java 复制代码
/*
/**
 * 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) {
        traverse(root);
        return res;
    }

    // Record the traverse recursive path
    LinkedList<String> path = new LinkedList<>();
    // Records all paths from the root to the leaf node
    LinkedList<String> res = new LinkedList<>();

    private void traverse(TreeNode root) {
        if (root == null) {
            return;
        }
        // leaf root
        if (root.left == null && root.right == null) {
            path.addLast(root.val + "");
            // Add this path to res
            res.addLast(String.join("->", path));
            path.removeLast();
            return;
        }
        // Preorder traversal position
        path.addLast(root.val + "");
        // Recursively traverse the left and right subtrees
        traverse(root.left);
        traverse(root.right);
        // Post order traversal position
        path.removeLast();
    }
}
相关推荐
铉铉这波能秀3 小时前
LeetCode Hot100数据结构背景知识之字典(Dictionary)Python2026新版
数据结构·python·算法·leetcode·字典·dictionary
蜡笔小马3 小时前
10.Boost.Geometry R-tree 空间索引详解
开发语言·c++·算法·r-tree
我是咸鱼不闲呀3 小时前
力扣Hot100系列20(Java)——[动态规划]总结(下)( 单词拆分,最大递增子序列,乘积最大子数组 ,分割等和子集,最长有效括号)
java·leetcode·动态规划
唐梓航-求职中3 小时前
编程-技术-算法-leetcode-288. 单词的唯一缩写
算法·leetcode·c#
仟濹3 小时前
【算法打卡day3 | 2026-02-08 周日 | 算法: BFS】3_卡码网99_计数孤岛_BFS | 4_卡码网100_最大岛屿的面积DFS
算法·深度优先·宽度优先
Ll13045252983 小时前
Leetcode二叉树part4
算法·leetcode·职场和发展
颜酱3 小时前
二叉树遍历思维实战
javascript·后端·算法
宝贝儿好3 小时前
第二章: 图像处理基本操作
算法
小陈phd4 小时前
多模态大模型学习笔记(二)——机器学习十大经典算法:一张表看懂分类 / 回归 / 聚类 / 降维
学习·算法·机器学习
@––––––4 小时前
力扣hot100—系列4-贪心算法
算法·leetcode·贪心算法