LeetCode筆記:257. Binary Tree Paths

問題:

Given a binary tree, return all root-to-leaf paths.
For example, given the following binary tree:


image.png

All root-to-leaf paths are:

["1->2->5", "1->3"]

大意:

給出一個二叉樹,返回所有從根節(jié)點到葉子節(jié)點的路徑。
比如給出下面這個二叉樹:


image.png

所有從根節(jié)點到葉子節(jié)點的路徑為:

["1->2->5", "1->3"]

思路:

這道題適合用遞歸,依次判斷有沒有左右葉子節(jié)點,分別去做遞歸,在遞歸中把遇到的節(jié)點值拼接到路徑字符串的最后,注意要拼接“->”這個內(nèi)容,直到?jīng)]有左右子節(jié)點后,表示已經(jīng)到了葉子節(jié)點了,就可以終止了,把這條路徑的字符串添加到結(jié)果中去。

代碼:

/**
 * Definition for a binary tree node.
 * public class TreeNode {
 *     int val;
 *     TreeNode left;
 *     TreeNode right;
 *     TreeNode(int x) { val = x; }
 * }
 */
public class Solution {
    public List<String> binaryTreePaths(TreeNode root) {
        List<String> result = new ArrayList<String>();
        if (root == null) return result;
        
        String path = String.valueOf(root.val);
        findPath(result, root, path);
        return result;
    }
    
    public void findPath(List<String> list, TreeNode root, String path) {
        if (root.left == null && root.right == null) {
            list.add(path);
            return;
        }
        if (root.left != null) {
            StringBuffer pathBuffer = new StringBuffer(path);
            pathBuffer.append("->");
            pathBuffer.append(String.valueOf(root.left.val));
            findPath(list, root.left, pathBuffer.toString());
        } 
        if (root.right != null) {
            StringBuffer pathBuffer = new StringBuffer(path);
            pathBuffer.append("->");
            pathBuffer.append(String.valueOf(root.right.val));
            findPath(list, root.right, pathBuffer.toString());
        }
    }
}

合集:https://github.com/Cloudox/LeetCode-Record


查看作者首頁

?著作權(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)容

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