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"]
Nothing special.... Just follow binary tree recursive.
static void binaryTreePaths(TreeNode* root, vector<string>& res, string path) {
if(!root) return;
if(!root->left && !root->right) {
path += to_string(root->val);
res.push_back(path);
return;
}
binaryTreePaths(root->right, res, path + to_string(root->val) + "->");
binaryTreePaths(root->left, res, path + to_string(root->val) + "->");
}
vector<string> binaryTreePaths(TreeNode* root) {
if(!root) return {};
vector<string> res;
string path = "";
binaryTreePaths(root, res, path);
return res;
}
本文介绍了一种用于查找二叉树中所有从根节点到叶子节点路径的算法。通过递归方式遍历二叉树,并将路径字符串拼接起来。最终返回所有找到的有效路径。
429

被折叠的 条评论
为什么被折叠?



