[刷题] 257 Binary Tree Paths
要求
- 给定一棵二叉树,返回所有表示从根节点到叶子节点路径的字符串
示例
- ["1->2->5","1->3"]
思路
- 递归地返回左右子树到叶子节点的字符串
示例
1 class Solution { 2 public: 3 vector<string> binaryTreePaths(TreeNode* root) { 4 5 vector<string> res; 6 7 if( root == NULL ) 8 return res; 9 10 if( root->left == NULL && root->right == NULL){ 11 res.push_back( to_string(root->val) ); 12 return res; 13 } 14 15 vector<string> leftS = binaryTreePaths(root->left); 16 for( int i = 0 ; i < leftS.size() ; i ++ ) 17 res.push_back( to_string(root->val) + "->" + leftS[i]); 18 19 vector<string> rightS = binaryTreePaths(root->right); 20 for( int i = 0 ; i < rightS.size() ; i ++ ) 21 res.push_back( to_string(root->val) + "->" + rightS[i]); 22 23 return res; 24 } 25 };
相关
- 113 Path Sum II
- 129 Sum Root to Leaf Numbers
【推荐】编程新体验,更懂你的AI,立即体验豆包MarsCode编程助手
【推荐】凌霞软件回馈社区,博客园 & 1Panel & Halo 联合会员上线
【推荐】抖音旗下AI助手豆包,你的智能百科全书,全免费不限次数
【推荐】轻量又高性能的 SSH 工具 IShell:AI 加持,快人一步