该题采用深搜就可以做了(其实树的很多问题用深搜的思路都可以解决的),从根节点开始记录路径上的每一个节点,每到一个叶子节点把路径放入结果vector中就可以了。
/** * 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: string int2str(int src){ stringstream dst; dst << src; return dst.str(); } void execTraverl(TreeNode* root, vector<string> &result, string tmp){ if(root -> left == nullptr && root -> right == nullptr){ tmp += "->"; tmp += int2str(root -> val); result.push_back(tmp); return; } if(root -> left != nullptr){ string tmp1 = tmp; tmp1 += "->"; tmp1 += int2str(root -> val); execTraverl(root -> left, result, tmp1); } if(root -> right != nullptr){ string tmp2 = tmp; tmp2 += "->"; tmp2 += int2str(root -> val); execTraverl(root -> right, result, tmp2); } } vector<string> binaryTreePaths(TreeNode* root){ string tmp; vector<string> result; if(root == nullptr) return result; if(root -> left == nullptr && root -> right == nullptr){ tmp += int2str(root -> val); result.push_back(tmp); return result; } if(root -> left != nullptr){ string tmp1; tmp1 += int2str(root -> val); execTraverl(root -> left, result, tmp1); } if(root -> right != nullptr){ string tmp2; tmp2 += int2str(root -> val); execTraverl(root -> right, result, tmp2); } return result; } };
版权声明:本文为博主原创文章,未经博主允许不得转载。
原文地址:http://blog.csdn.net/ny_mg/article/details/48086379