题目:
Given a binary tree, return all root-to-leaf paths.
For example, given the following binary tree:
1 / 2 3 5
All root-to-leaf paths are:
["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: void recursiveTree(vector<string> &res, TreeNode* node, string str) { if (node->left == NULL && node->right == NULL) { res.push_back(str); return; } if (node->left != NULL) { recursiveTree(res, node->left, str + "->" + to_string(node->left->val)); } if (node->right != NULL) { recursiveTree(res, node->right, str + "->" + to_string(node->right->val)); } } vector<string> binaryTreePaths(TreeNode* root) { vector<string> res; if (root == NULL) return res; recursiveTree(res, root, to_string(root->val)); return res; } };