1 题目
题目:找出二叉树的所有路径(Binary Tree Paths)
描述:给一棵二叉树,找出从根节点到叶子节点的所有路径。
lintcode题号——480,难度——easy
样例1:
输入:{1,2,3,#,5}
输出:["1->2->5","1->3"]
解释:
1
/ \
2 3
\
5
样例2:
输入:{1,2}
输出:["1->2"]
解释:
1
/
2
2 解决方案
2.1 思路
使用分治法,只要根据左右子树返回的结果与当前节点的值拼接出结果即可。
2.2 时间复杂度
需要完整地遍历整棵树,算法的时间复杂度为O(n)。
2.3 空间复杂度
算法的空间复杂度为O(1)。
3 源码
细节:
- 叶子节点需要特殊处理,返回不带
->
的数据。 - c++11中int转string,可以使用
to_string()
函数代替itoa()
。
C++版本:
/**
* @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 == nullptr)
{
return result;
}
// 处理叶子节点
if (root->left == nullptr && root->right == nullptr)
{
result.push_back(to_string(root->val));
return result;
}
vector<string> leftPaths = binaryTreePaths(root->left);
vector<string> rightPaths = binaryTreePaths(root->right);
// 处理普通节点
for (vector<string>::iterator it = leftPaths.begin(); it != leftPaths.end(); it++)
{
string temp = to_string(root->val) + "->" + *it;
result.push_back(temp);
}
for (vector<string>::iterator it = rightPaths.begin(); it != rightPaths.end(); it++)
{
string temp = to_string(root->val) + "->" + *it;
result.push_back(temp);
}
return result;
}