Java实现 LeetCode 257 二叉树的所有路径

257. 二叉树的所有路径

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

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

示例:

输入:

   1
 /   \
2     3
 \
  5

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

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

/**
 * 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) {
        String path=new String("");
        List<String> list = new ArrayList<>();
        helper(root,path,list);
        return list;
    }

    public void helper(TreeNode root,String path,List<String> paths)
    {
        if(root!=null)
        {
            path+=Integer.toString(root.val);
            if(root.left==null && root.right == null)
                paths.add(path);
            else{
                path+="->";
                helper(root.left,path,paths);
                helper(root.right,path,paths);
            }
        }
    }
}
发布了1385 篇原创文章 · 获赞 1万+ · 访问量 140万+

猜你喜欢

转载自blog.csdn.net/a1439775520/article/details/104642251
今日推荐