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: vector<string> binaryTreePaths(TreeNode* root) { vector<string> vs; if (root == NULL) return vs; if (root->left == NULL && root->right == NULL) { char buff[124]; sprintf(buff, "%d", root->val); vs.push_back(buff); return vs; } if (root->left) { vector<string> lefts = binaryTreePaths(root->left); for (int i = 0; i < lefts.size(); i++) { char *buff = new char[lefts[i].size()+56]; sprintf(buff, "%d->%s", root->val, lefts[i].c_str()); vs.push_back(buff); delete[] buff; } } if (root->right) { vector<string> rights = binaryTreePaths(root->right); for (int i = 0; i < rights.size(); i++) { char *buff = new char[rights[i].size()+56]; sprintf(buff, "%d->%s", root->val, rights[i].c_str()); vs.push_back(buff); delete[] buff; } } return vs; } };
/** * 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> results; visitTreeNode(root, "", results); return results; } private: void visitTreeNode(TreeNode* node, string path, vector<string>& result) { if(node == nullptr) return; if (!path.empty()) //检测之前的路径是不是为空; { //如果为空,则为第一个路径,不许要加-> path += "->"; //如果不为空则需要在后面加-> } path += int2Str(node->val); //必须使用将int型转换为string型 if (node->left == nullptr && node->right == nullptr) { result.push_back(path); } else { if (node->left != nullptr) { visitTreeNode(node->left, path, result); } if (node->right != nullptr) { visitTreeNode(node->right, path, result); } } } std::string int2Str(int nValue) { ostringstream ss; ss << nValue; //直接给string型赋值是不可以的,必须通过流转换 return ss.str(); } };
原文:http://www.cnblogs.com/dylqt/p/4872466.html