1. 程式人生 > 實用技巧 >LeetCode 257. 二叉樹的所有路徑 dfs

LeetCode 257. 二叉樹的所有路徑 dfs

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

給定一個二叉樹,返回所有從根節點到葉子節點的路徑。

說明:葉子節點是指沒有子節點的節點。

示例:

輸入:

   1
 /   \
2     3
 \
  5

輸出: ["1->2->5", "1->3"]

解釋: 所有根節點到葉子節點的路徑為: 1->2->5, 1->3

演算法1
DFS遍歷

注意由於最後一個元素不加”->”
我是在新增數字的前面才新增”->”
所以要特判第一次加入 if (!path.empty())

C++ 程式碼

class Solution {
public:
    vector<string> ans;
void Dfs(TreeNode* root, string path) {
    if (root == NULL) {return;}

    if (!path.empty()) { path += "->"; }
    path += to_string(root->val);

    if (root->right == NULL && root->left == NULL) {
        ans.push_back(path);
return; } Dfs(root->right, path); Dfs(root->left, path); } vector<string> binaryTreePaths(TreeNode* root) { string path; Dfs(root, path); return ans; } };