1. 程式人生 > 實用技巧 >257. 二叉樹的所有路徑(C++)

257. 二叉樹的所有路徑(C++)

目錄

題目

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

說明:

  • 葉子節點是指沒有子節點的節點。

示例:

輸入:

   1
 /   \
2     3
 \
  5

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

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

分析與題解

此題使用深度優先遍歷演算法,每次遍歷到一個節點就把該節點的值存入string中,然後判斷是否為葉

節點:如果為葉子節點就需要把該條路路徑新增進vector中。

本題需要注意vector中儲存的是string,對自定義函式的傳參有一個清晰的認識:

  • 輸出結果只需要一個包含所有路徑string的vector,所以vector採用引用傳參

  • 每次遞迴過程中,當前結點產生的string都會進行變化(除非是葉結點),每次都要生成一個傳入string的副本,因此採用值傳遞。這樣就意味著每個函式中的path均不相同。

    另外,考慮到string,我們需要使用to_string函式對root->val進行資料型別的轉換

程式碼如下:

/**
 * Definition for a binary tree node.
 * struct TreeNode {
 *     int val;
 *     TreeNode *left;
 *     TreeNode *right;
 *     TreeNode(int x) : val(x), left(NULL), right(NULL) {}
 * };
 */
class Solution {
public:
    //因為每次迭代的string其實不一樣,所以使用值傳遞
    //但是每次迭代的vector只需要一個最終結果,所以使用引用傳遞
    void findPath(TreeNode* root, string path, vector<string> &res){
        if(root==NULL)
            return ;
        if(path!="")
            path.append("->");
        path.append(to_string(root->val));
        if(root->left==NULL && root->right==NULL)
            res.push_back(path);
        findPath(root->left, path, res);
        findPath(root->right, path, res);
    }

    vector<string> binaryTreePaths(TreeNode* root) {
        string path;
        vector<string> res;
        findPath(root, path, res);
        return res;
    }
};