LeetCode257. 二叉树的所有路径

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

例如,给定以下二叉树:

   1
 /   \
2     3
 \
  5

所有根到叶路径是:

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

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