首页 > 其他 > 详细

二叉树的所有路径

时间:2020-09-04 15:10:23      阅读:52      评论:0      收藏:0      [点我收藏+]

题目链接: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

二叉树的所有路径

原文:https://www.cnblogs.com/cstdio1/p/13613248.html

(0)
(0)
   
举报
评论 一句话评论(0
关于我们 - 联系我们 - 留言反馈 - 联系我们:wmxa8@hotmail.com
© 2014 bubuko.com 版权所有
打开技术之扣,分享程序人生!