zoukankan      html  css  js  c++  java
  • 二叉树的所有路径

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

  • 相关阅读:
    自我介绍
    币值转换
    打印沙漏
    对我影响最大的三位老师

    pta
    pta-3
    学习计划
    对我有影响的三个老师
    介绍自己
  • 原文地址:https://www.cnblogs.com/cstdio1/p/13613248.html
Copyright © 2011-2022 走看看