257. 二叉树的所有路径(java)

给定一个二叉树,返回所有从根节点到叶子节点的路径。

说明: 叶子节点是指没有子节点的节点。

示例:

输入:

   1
 /   \
2     3
 \
  5

输出: ["1->2->5", "1->3"]

解释: 所有根节点到叶子节点的路径为: 1->2->5, 1->3

来源:力扣(LeetCode)
链接:https://leetcode-cn.com/problems/binary-tree-paths
著作权归领扣网络所有。商业转载请联系官方授权,非商业转载请注明出处。
/**
 * Definition for a binary tree node.
 * public class TreeNode {
 *     int val;
 *     TreeNode left;
 *     TreeNode right;
 *     TreeNode(int x) { val = x; }
 * }
 */
class Solution {
    public List<String> binaryTreePaths(TreeNode root) {
        LinkedList<String> res = new LinkedList<>();
        if(root == null) return res;
        solve(root, "", res);
        return res;
    }
    public void solve(TreeNode root, String cur, LinkedList<String> res){
        if(root == null) return;
        cur += root.val;  
        if(root.left == null && root.right == null)
            res.add(cur);
        else{
            solve(root.left, cur+"->", res);
            solve(root.right, cur+"->", res); 
        }     
    }
}
发布了136 篇原创文章 · 获赞 19 · 访问量 8031

猜你喜欢

转载自blog.csdn.net/weixin_43306331/article/details/104027118