原题网址:https://www.lintcode.com/problem/binary-tree-paths/description
描述
给一棵二叉树,找出从根节点到叶子节点的所有路径。
您在真实的面试中是否遇到过这个题?
样例
给出下面这棵二叉树:
1
/
2 3
5
所有根到叶子的路径为:
[ "1->2->5", "1->3" ]
标签
二叉树遍历
二叉树
思路:二叉树遍历问题,递归。
设计一个递归函数,用一个字符串保存遍历到的节点值,遍历时将当前节点值转成string加入该字符串。
如果该节点是叶子结点,表示找到一条路径,将字符串push到result结果数组中;
如果不是叶子结点,若左子树存在,对其递归继续遍历;若右子树存在,对其递归继续遍历。
PS:关于两个节点字符值之间的箭头处理,可参考:去掉std::string或std::wstring的最后一个字符的简单方法
AC代码:
/**
* 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="";
tra(result,s,root);
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)
{
s.pop_back();
s.pop_back();
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;
}
};
初始AC代码:(箭头连接符处理导致代码冗余)
/**
* 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;
}
};
lintcode今天抽风,提交失败,快被气死……