二叉树的所有路径

题目链接: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) {
        List<String> res = new ArrayList<>();
        if(root == null) return res;
         helper(root,res,"");
         return res;
    }
    public void helper(TreeNode root,List<String> res,String tmp){
        if(root.left == null && root.right == null){
            tmp += root.val+"";
            res.add(tmp);
            tmp = "";
            return;
        }
        tmp +=root.val+""+"->";
        //res.add();
        if(root.left != null){
            helper(root.left,res,tmp);
        }
        if(root.right != null){
        helper(root.right,res,tmp);
        }
    }
}


犯的错:之前并没有引入tmp保存而是直接 res.add(root.val+""+"->")导致输出与题目不一致

将String换成StringBuilder可以提高到2ms

posted @ 2020-09-04 13:07  浅滩浅  阅读(151)  评论(0)    收藏  举报