1. 程式人生 > 實用技巧 >Leetcode——257. 二叉樹的所有路徑(遞迴)

Leetcode——257. 二叉樹的所有路徑(遞迴)

@目錄

257. 二叉樹的所有路徑

https://leetcode-cn.com/problems/binary-tree-paths/

題目

給定一個二叉樹,返回所有從根節點到葉子節點的路徑。
說明: 葉子節點是指沒有子節點的節點。
示例:
輸入:
   1
 /   \
2     3
 \
  5
輸出: ["1->2->5", "1->3"]
解釋: 所有根節點到葉子節點的路徑為: 1->2->5, 1->3

思想

輸出二叉樹的所有路徑:
此處用的是字串,如果都為整數,可以參考113. 路徑總和 II

方法

List<List<Integer>> result = new ArrayList<>();//result儲存各個路徑
LinkedList<Integer> stack = new LinkedList<>();//連結串列陣列stack來儲存(便於增刪)當前

路徑
此處直接用字串儲存即可,另外注意輸出格式

程式碼

/**
 * Definition for a binary tree node.
 * public class TreeNode {
 *     int val;
 *     TreeNode left;
 *     TreeNode right;
 *     TreeNode(int x) { val = x; }
 * }
 */
/*
輸出二叉樹的所有路徑:

*/

class Solution {
    public void Paths(TreeNode root, String path, List<String> res) {
        if(root == null){
            return;
        }
        path += Integer.toString(root.val);
        if(root.left == null && root.right == null){
            res.add(path);
        }
        else{
            path += "->";
            Paths(root.left, path, res);
            Paths(root.right, path, res);
        }
    }

    public List<String> binaryTreePaths(TreeNode root) {
        List<String> result = new ArrayList<>();
        Paths(root, "", result);
        return result;
    }
}