您的位置:首页 > 编程语言

leetcode:257 Binary Tree Paths-每日编程第四十五题

2015-12-29 14:48 471 查看
Binary Tree Paths

Total
Accepted: 27476 Total
Submissions: 108456 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"]

<span style="font-size:14px;">/**
* Definition for a binary tree node.
* struct TreeNode {
*     int val;
*     TreeNode *left;
*     TreeNode *right;
*     TreeNode(int x) : val(x), left(NULL), right(NULL) {}
* };
*/
class Solution {
public:
void int2string(string& str,int val){
if(val==0){
return;
}
char ch=(val%10)+'0';
int2string(str,val/10);
str+=ch;
return;
}

string int2string(int val){
string str;
if(val<0){
str+="-";
val*=-1;
}
int2string(str,val);
return str;
}

void binaryTreePaths(TreeNode* root,vector<string>& vec,string str){
string ch=int2string(root->val);
str+="->";
str+=ch;
if(root->left==NULL&&root->right==NULL){
vec.push_back(str);
return;
}
if(root->left!=NULL){
binaryTreePaths(root->left,vec,str);
}
if(root->right!=NULL){
binaryTreePaths(root->right,vec,str);
}
}

vector<string> binaryTreePaths(TreeNode* root) {
vector<string> vec;
if(root==NULL){
return vec;
}
string ch=int2string(root->val);
string str;
str+=ch;
if(root->left==NULL&&root->right==NULL){
vec.push_back(str);
return vec;
}
if(root->left!=NULL){
binaryTreePaths(root->left,vec,str);
}
if(root->right!=NULL){
binaryTreePaths(root->right,vec,str);
}
return vec;
}
};</span>
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: