0
点赞
收藏
分享

微信扫一扫

LeetCode257. 二叉树的所有路径

小安子啊 2022-01-09 阅读 66

题目:

力扣

题解:

dfs 前序遍历每个节点,记录每个节点值到路径,遇到叶子节点保存路径,每个节点值使用后需要回溯(删除路径),时间复杂度:O(N^2)。

public class Solution {

    public List<String> pathList = new ArrayList<>();

    public List<String> binaryTreePaths(TreeNode root) {
        List<Integer> nodeValueList = new ArrayList<>();
        dfs(root, nodeValueList);
        return pathList;
    }


    public void dfs(TreeNode root, List<Integer> nodeValueList) {
        if (root == null) {
            return;
        }

        // 添加当前节点路径
        nodeValueList.add(root.val);
        // 叶子节点保存路径
        if (root.left == null && root.right == null) {
            String path = nodeValueList.stream().map(String::valueOf).collect(Collectors.joining("->"));
            pathList.add(path);
        }

        dfs(root.left, nodeValueList);
        dfs(root.right, nodeValueList);
        // 回溯
        nodeValueList.remove(nodeValueList.size() - 1);
    }

}
举报

相关推荐

0 条评论