leetcode--257.Binary Tree Paths
使用深度优先搜索的方法遍历每一条枝,遍历完的终止条件为左右子树都为空,这时候将这条枝的string 插入vector 中。
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 | class Solution { public : // vector 一直插入string,所以为引用类型,string不能是引用类型 void dfs(TreeNode *root, vector<string> & result, string temp) { if (root->left==NULL&&root->right==NULL) result.push_back(temp); if (root->left) dfs(root->left,result,temp+ "->" +to_string(root->left->val)); if (root->right) dfs(root->right,result,temp+ "->" +to_string(root->right->val)); } vector<string> binaryTreePaths(TreeNode* root) { vector<string>result; if (root==NULL) return result; string temp=to_string(root->val); dfs(root, result, temp); return result; } }; |
第二种方法,在函数内部进行递归:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 | vector<string> binaryTreePaths(TreeNode *root) { vector<string> result; if (root==NULL) return result; if (root->left==NULL&& root->right==NULL) return {to_string(root->val)}; vector<string> left=binaryTreePaths(root->left); vector<string> right=binaryTreePaths(root->right); left.insert(left.end(),right.begin(),right.end()); vector<string>::iterator iter; for (iter=left.begin();iter!=left.end();iter++) { *iter=to_string(root->val)+ "->" +*iter; } return left; } |
【推荐】编程新体验,更懂你的AI,立即体验豆包MarsCode编程助手
【推荐】凌霞软件回馈社区,博客园 & 1Panel & Halo 联合会员上线
【推荐】抖音旗下AI助手豆包,你的智能百科全书,全免费不限次数
【推荐】博客园社区专享云产品让利特惠,阿里云新客6.5折上折
【推荐】轻量又高性能的 SSH 工具 IShell:AI 加持,快人一步