力扣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();
    }
}
相关推荐
黑听人2 小时前
【力扣 困难 C】329. 矩阵中的最长递增路径
c语言·leetcode
YuTaoShao4 小时前
【LeetCode 热题 100】141. 环形链表——快慢指针
java·算法·leetcode·链表
小小小新人121235 小时前
C语言 ATM (4)
c语言·开发语言·算法
你的冰西瓜5 小时前
C++排序算法全解析(加强版)
c++·算法·排序算法
এ᭄画画的北北5 小时前
力扣-31.下一个排列
算法·leetcode
绝无仅有6 小时前
企微审批对接错误与解决方案
后端·算法·架构
趣多多代言人7 小时前
从零开始手写嵌入式实时操作系统
开发语言·arm开发·单片机·嵌入式硬件·面试·职场和发展·嵌入式
用户5040827858397 小时前
1. RAG 权威指南:从本地实现到生产级优化的全面实践
算法
Python×CATIA工业智造8 小时前
详细页智能解析算法:洞悉海量页面数据的核心技术
爬虫·算法·pycharm