[刷题] 257 Binary Tree Paths

Posted cxc1357

tags:

篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了[刷题] 257 Binary Tree Paths相关的知识,希望对你有一定的参考价值。

要求

  • 给定一棵二叉树,返回所有表示从根节点到叶子节点路径的字符串

思路

  • 递归地返回左右子树到叶子节点的字符串

示例

技术图片
 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 };
View Code

相关

  • 113 Path Sum II
  • 129 Sum Root to Leaf Numbers

以上是关于[刷题] 257 Binary Tree Paths的主要内容,如果未能解决你的问题,请参考以下文章

257. Binary Tree Paths

257. Binary Tree Paths 257.二叉树路径

257. Binary Tree Paths 257.二叉树路径

257. Binary Tree Paths

257.Binary Tree Paths

257. Binary Tree Paths