257. Binary Tree Paths
Total Accepted: 42674 Total Submissions: 151478 Difficulty: Easy
Given a binary tree, return all root-to-leaf paths.
For example, given the following binary tree:
1 / \ 2 3 \ 5
All root-to-leaf paths are:
["1->2->5", "1->3"]
解法及注解:特别声明,该解法转自:http://blog.csdn.net/booirror/article/details/47733175
struct TreeNode
{
int val;
TreeNode *left;
TreeNode *right;
TreeNode(int x) : val(x), left(NULL), right(NULL) {}
};
class Solution4
{
public:
vector<string> binaryTreePaths(TreeNode* root)
{
vector<string> path;//定义一个string类型的容器,用于存放路径
//如果根节点为NULL,直接返回;
if(root==NULL)return path;
//将叶子节点存入容器
if(root->left==NULL&&root->right==NULL)
{
char buff[8];//考虑到系统最大支持int型整数为64个字节,即8个字节
sprintf(buff,"%d",root->val);//通过sprintf()将节点数据转换成字符串形式
path.push_back(buff);//叶子节点以字符串的形式存入容器
return path;
}
if(root->left!=NULL)
{
vector<string> leftPath=binaryTreePaths(root->left);
for(int i=0;i<leftPath.size();i++)
{
char *buff=new char[leftPath[i].size()+6];//为何+6?除了leftPath[i]需要的空间外,root->val占用4个字节,路径符号“->”占两个字节,因此需要额外的6个字节。
sprintf(buff,"%d->%s",root->val,leftPath[i].c_str());//将路径构造成字符串,sprintf()函数具备此功能。
path.push_back(buff);//路径保存入容器
delete[] buff;//删除buff所占内存
}
}
if(root->right!=NULL)
{
vector<string> rightPath=binaryTreePaths(root->right);
for(int i=0;i<rightPath.size();i++)
{
char *buff=new char[rightPath[i].size()+6];
sprintf(buff,"%d->%s",root->val,rightPath[i].c_str());
path.push_back(buff);
delete[] buff;
}
}
return path;
}
};