要求
- 给定一棵二叉树,返回所有表示从根节点到叶子节点路径的字符串
示例
- ["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