题目:
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"]题目链接
题意:
给一棵二叉树,要求求出所以从根到叶的路径,并将路径压入vector中返回。
普通先序遍历的基础上,每到一个节点,进行判断是否为叶子结点,假如是叶子结点,那么就将path压入vector,否则,将当前path递归进下一层。
代码如下;
class Solution {
public:
vector<string> ans;
void dfs(TreeNode* node, string path) {
path += to_string(node->val);
if (!node->left && !node->right) {
ans.push_back(path);
return;
}
path += "->";
if (node->left) {
dfs(node->left, path);
}
if (node->right) {
dfs(node->right, path);
}
}
vector<string> binaryTreePaths(TreeNode* root) {
if (!root) return ans;
dfs(root, "");
return ans;
}
};