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"]
这道题是找出找出二叉树根节点到叶节点的所有路径,题目难度为easy。
可以分别采用深度优先和广度优先的方法遍历二叉树,由于广度优先搜索需要用队列存储当前遍历到的节点的路径,相对比较繁琐,所以这里仅采用深度优先的方式进行处理。具体代码:
class Solution {
void getPaths(TreeNode* node, vector<string>& paths, string curPath) {
if(!curPath.empty()) curPath += "->";
curPath += to_string(node->val);
if(!node->left && !node->right) {
paths.push_back(curPath);
return;
}
if(node->left)
getPaths(node->left, paths, curPath);
if(node->right)
getPaths(node->right, paths, curPath);
}
public:
vector<string> binaryTreePaths(TreeNode* root) {
vector<string> paths;
if(!root) return paths;
getPaths(root, paths, "");
return paths;
}
};