【每日leetcode】二叉樹的所有路徑

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

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

示例:

輸入:

1
/
2 3

5

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

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

/**
 * 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:
    vector<string> binaryTreePaths(TreeNode* root) {
        vector<string> res;
        string temp;
        findpath(root,temp,res);
        return res;
    }
    void findpath(TreeNode* root,string temp,vector<string> &res)
    {
        if(root==nullptr)
            return;
        temp=temp+to_string(root->val)+"->";
        //是葉子節點
        if(root->left==nullptr&&root->right==nullptr)
        {
            temp.erase(temp.length()-2);
            res.push_back(temp);
        }
        if(root->left!=nullptr)
            findpath(root->left,temp,res);
        if(root->right!=nullptr)
            findpath(root->right,temp,res);
        
    }
};
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章