力扣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();
    }
}
相关推荐
yaoh.wang16 小时前
力扣(LeetCode) 88: 合并两个有序数组 - 解法思路
python·程序人生·算法·leetcode·面试·职场和发展·双指针
LYFlied16 小时前
【每日算法】 LeetCode 56. 合并区间
前端·算法·leetcode·面试·职场和发展
艾醒17 小时前
大模型原理剖析——多头潜在注意力 (MLA) 详解
算法
艾醒17 小时前
大模型原理剖析——DeepSeek-V3深度解析:671B参数MoE大模型的技术突破与实践
算法
jifengzhiling18 小时前
零极点对消:原理、作用与风险
人工智能·算法
鲨莎分不晴18 小时前
【前沿技术】Offline RL 全解:当强化学习失去“试错”的权利
人工智能·算法·机器学习
XFF不秃头19 小时前
力扣刷题笔记-全排列
c++·笔记·算法·leetcode
菜鸟233号19 小时前
力扣669 修剪二叉搜索树 java实现
java·数据结构·算法·leetcode
光羽隹衡19 小时前
机械学习逻辑回归——银行贷款案例
算法·机器学习·逻辑回归