給定一個二叉樹,返回所有從根節點到葉子節點的路徑。
說明:?葉子節點是指沒有子節點的節點。
示例:
輸入:
? ?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;dfs(root, res, "");return res; }void dfs(TreeNode *root, vector<string> &res, string curr){if(!root) return;curr += to_string(root->val);if(root->left == NULL && root->right == NULL){res.push_back(curr);return;}dfs(root->left, res, curr + "->");dfs(root->right, res, curr + "->");}
};
?