给定一个二叉树,返回所有从根节点到叶子节点的路径。
说明: 叶子节点是指没有子节点的节点。
示例:
输入:
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>result; string str = ""; digui(root,str,result); return result; } void digui(TreeNode* node, string &path, vector<string>&result) { if (node != NULL) path += to_string(node->val); else return; if (node->left == NULL && node->right == NULL) { result.push_back(path); } path += "->"; string p1=path,p2 = path; if (node->left != NULL) { digui(node->left,p1,result); } if (node->right != NULL) { digui(node->right, p2, result); } } };