力扣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();
    }
}
相关推荐
不会学习?29 分钟前
算法03 归并分治
算法
NuyoahC1 小时前
笔试——Day43
c++·算法·笔试
2301_821919921 小时前
决策树8.19
算法·决策树·机器学习
秋难降2 小时前
别再用暴力排序了!大小顶堆让「取极值」效率飙升至 O (log n)
python·算法·排序算法
学行库小秘2 小时前
基于门控循环单元的数据回归预测 GRU
人工智能·深度学习·神经网络·算法·回归·gru
_meow_3 小时前
数学建模 15 逻辑回归与随机森林
算法·数学建模·逻辑回归
1白天的黑夜13 小时前
链表-24.两两交换链表中的结点-力扣(LeetCode)
数据结构·leetcode·链表
二向箔reverse3 小时前
机器学习算法核心总结
人工智能·算法·机器学习
猿究院--冯磊4 小时前
JVM垃圾收集器
java·jvm·算法
野犬寒鸦5 小时前
力扣hot100:最大子数组和的两种高效方法:前缀和与Kadane算法(53)
java·后端·算法