java数据结构与算法刷题-----LeetCode257. 二叉树的所有路径

java数据结构与算法刷题目录(剑指Offer、LeetCode、ACM)-----主目录-----持续更新(进不去说明我没写完):https://blog.youkuaiyun.com/grd_java/article/details/123063846

在这里插入图片描述

解题思路
  1. 直接使用深度优先遍历
  2. 每次都将结点记录到路径字符串中
  3. 如果当前结点是叶子结点,说明一条路径遍历完成,直接添加到链表中
  4. 如果当前结点不是叶子结点,说明这条路径没有遍历完成,则添加->符号后,继续深度优先遍历
代码

在这里插入图片描述

/**
 * 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) {
        List<String> paths = new ArrayList<String>();//保存答案
        constructPaths(root, "", paths);
        return paths;
    }
    /**
        path保存路径
        paths 保存答案
     */
    public void constructPaths(TreeNode root, String path, List<String> paths) {
        if (root != null) {//如果当前结点不为空
            StringBuffer pathSB = new StringBuffer(path);//保存路径
            pathSB.append(Integer.toString(root.val));//将当前结点保存
            if (root.left == null && root.right == null) {  // 如果当前节点是叶子节点,说明找到一条路径
                paths.add(pathSB.toString());  // 把路径加入到答案中
            } else {//如果当前依然不是叶子结点,说明后面还有,那么需要一个->符号
                pathSB.append("->");  // 当前节点不是叶子节点,继续递归遍历
                constructPaths(root.left, pathSB.toString(), paths);//左子树
                constructPaths(root.right, pathSB.toString(), paths);//右子树
            }
        }
    }
}
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

ydenergy_殷志鹏

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值