LeetCode257. 二叉树的所有路径2

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

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

示例:

输入:

   1
 /   \
2     3
 \
  5

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

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

思路:深度优先遍历二叉树,在遍历过程中将每个节点的值存储下来,遍历到叶子结点时,将一路遍历存储的路径加入List。

    /**
     * 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) {
            List<String> list=new ArrayList<>();
             if(root==null) {
                 return list;
             }
             iterator(root,list,"");
             return list;    
        }
        
         public  void iterator(TreeNode root,List<String> list,String s) {
            s+=root.val+" ";
            if(root.left==null&&root.right==null) {
                list.add(s.trim().replaceAll(" ", "->"));
            }
            if(root.left!=null) {
                iterator(root.left,list,s);
            }
            if(root.right!=null) {
                iterator(root.right,list,s);
            }
        }
    }
---------------------
作者:1号帅比
来源:CSDN
原文:https://blog.csdn.net/weixin_40550726/article/details/80536301
版权声明:本文为博主原创文章,转载请附上博文链接!

posted @ 2019-07-28 16:50  天涯海角路  阅读(108)  评论(0)    收藏  举报