2021.11.10 - SX07-13.二叉树的所有路径

1. 题目

在这里插入图片描述

2. 思路

(1) DFS

  • 利用深度优先搜索遍历二叉树,若遍历到叶子结点,则将当前路径加入结果集中即可。

3. 代码

import java.util.ArrayList;
import java.util.List;

public class Test {
    
    
    public static void main(String[] args) {
    
    
    }
}

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 {
    
    
    private List<String> res;

    public List<String> binaryTreePaths(TreeNode root) {
    
    
        res = new ArrayList<>();
        preorder(root, new StringBuilder());
        return res;
    }

    private void preorder(TreeNode root, StringBuilder path) {
    
    
        if (root == null) {
    
    
            return;
        }
        path.append(root.val);
        if (root.left == null && root.right == null) {
    
    
            res.add(path.toString());
        } else {
    
    
            if (root.left != null) {
    
    
                preorder(root.left, new StringBuilder(path).append("->"));
            }
            if (root.right != null) {
    
    
                preorder(root.right, new StringBuilder(path).append("->"));
            }
        }
    }
}

猜你喜欢

转载自blog.csdn.net/qq_44021223/article/details/121243100