Given a binary tree, return all root-to-leaf paths.
Note: A leaf is a node with no children.
給一個二元樹,回傳所有從根到葉的路徑。
注意:葉子是只一個節點沒有任何小孩。
Example:
Input:
1
/ \
2 3
\
5
Output: ["1->2->5", "1->3"]
Explanation: All root-to-leaf paths are: 1->2->5, 1->3
root == NULL
)root
的路徑不能有箭號在前面(你也可以在最後不加箭號在後面)
/**
* 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:
void addPath(TreeNode* node, string nowPath, vector<string>& allPath, bool first)
{
if(first)
nowPath += to_string(node->val);
else
nowPath += "->" + to_string(node->val);
if(node->right == NULL && node->left == NULL)
allPath.push_back(nowPath);
if(node->right)
addPath(node->right, nowPath, allPath, false);
if(node->left)
addPath(node->left, nowPath, allPath, false);
}
vector<string> binaryTreePaths(TreeNode* root) {
vector<string> allPath;
if(root)
addPath(root, string(), allPath, true);
return allPath;
}
};
LeetCode
C++