标签:lan push style div you string tree view HERE
原题网址:https://www.lintcode.com/problem/binary-tree-paths/description
给一棵二叉树,找出从根节点到叶子节点的所有路径。
给出下面这棵二叉树:
1
/ 2 3
5
所有根到叶子的路径为:
[ "1->2->5", "1->3" ]
/**
* Definition of TreeNode:
* class TreeNode {
* public:
* int val;
* TreeNode *left, *right;
* TreeNode(int val) {
* this->val = val;
* this->left = this->right = NULL;
* }
* }
*/
class Solution {
public:
/**
* @param root: the root of the binary tree
* @return: all root-to-leaf paths
*/
vector<string> binaryTreePaths(TreeNode * root) {
// write your code here
vector<string> result;
if (root==NULL)
{
return result;
}
string s="";
int2str(root->val,s);
if (root->left==NULL&&root->right==NULL)
{
result.push_back(s);
return result;
}
if (root->left)
{
tra(result,s,root->left);
}
if (root->right)
{
tra(result,s,root->right);
}
return result;
}
void tra(vector<string> &result,string s,TreeNode * root)//s不需要定义成引用类型,不需要保存其上一步结果,因为二叉树向下递归时s值自然累加节点值;
{
string tmp;
int2str(root->val,tmp);
s=s+"->"+tmp;
if (root->left==NULL&&root->right==NULL)
{
result.push_back(s);
return ;
}
if (root->left)
{
tra(result,s,root->left);
}
if (root->right)
{
tra(result,s,root->right);
}
}
void int2str(const int &int_tmp,string &string_tmp)
{
stringstream s;
s<<int_tmp;
string_tmp=s.str();//或者 s>>string_tmp;
}
};
标签:lan push style div you string tree view HERE
原文地址:https://www.cnblogs.com/Tang-tangt/p/9254829.html