二刷257. Binary Tree Paths

Easy題
但是一開始不知為什么選擇了StringBuilder沒選String, 而且總覺得要backtracking.
要記得初始化一個string可以用String path = root.val + "", 就是whatever + ""就可以初始化一個string.
額,看了一圈答案,發(fā)現(xiàn)我最開始用StringBuilder + backtracking的思路是對的,update一下吧

/**
 * 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;
        }
        StringBuilder path = new StringBuilder();
        dfsHelper(root, res, path);
        return res;    
    }
    
    private void dfsHelper(TreeNode root, List<String> res, StringBuilder curtPath){
        if (root == null){
            return;
        }    
        if (root.left == null && root.right == null){
            curtPath.append(root.val);
            res.add(curtPath.toString());
            return;
        }
        curtPath.append(root.val);
        curtPath.append("->");
        int origLen = curtPath.length();
        dfsHelper(root.left, res, curtPath);
        curtPath.setLength(origLen);
        dfsHelper(root.right, res, curtPath);
        curtPath.setLength(origLen);
    }
}
/**
 * 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<>();
        String path = root.val + "";
        dfsHelper(root, res, path);
        return res;    
    }
    
    private void dfsHelper(TreeNode root, List<String> res, String curtPath){
        if (root == null){
            return;
        }    
        if (root.left == null && root.right == null){
            res.add(curtPath);
            return;
        }
        if (root.left != null){
            dfsHelper(root.left, res, curtPath + "->" + root.left.val);
        }
        if (root.right != null){
            dfsHelper(root.right, res, curtPath + "->" + root.right.val);
        }
    }
}
最后編輯于
?著作權(quán)歸作者所有,轉(zhuǎn)載或內(nèi)容合作請聯(lián)系作者
【社區(qū)內(nèi)容提示】社區(qū)部分內(nèi)容疑似由AI輔助生成,瀏覽時請結(jié)合常識與多方信息審慎甄別。
平臺聲明:文章內(nèi)容(如有圖片或視頻亦包括在內(nèi))由作者上傳并發(fā)布,文章內(nèi)容僅代表作者本人觀點,簡書系信息發(fā)布平臺,僅提供信息存儲服務(wù)。

相關(guān)閱讀更多精彩內(nèi)容

  • 背景 一年多以前我在知乎上答了有關(guān)LeetCode的問題, 分享了一些自己做題目的經(jīng)驗。 張土汪:刷leetcod...
    土汪閱讀 12,921評論 0 33
  • Spring Cloud為開發(fā)人員提供了快速構(gòu)建分布式系統(tǒng)中一些常見模式的工具(例如配置管理,服務(wù)發(fā)現(xiàn),斷路器,智...
    卡卡羅2017閱讀 136,554評論 19 139
  • Java 語言支持的類型分為兩類:基本類型和引用類型。整型(byte 1, short 2, int 4, lon...
    xiaogmail閱讀 1,450評論 0 10
  • Spark SQL, DataFrames and Datasets Guide Overview SQL Dat...
    Joyyx閱讀 8,485評論 0 16
  • 昨晚睡覺做了個夢,很糊涂又很貼切??戳嗣餍切生日,說是婆家人為她慶生,有她的姐妹,母親,而好友親戚,唯獨沒有她的...
    番茄紅閱讀 412評論 0 0

友情鏈接更多精彩內(nèi)容