Leetcode 257. Binary Tree Paths
Given the root of a binary tree, return all root-to-leaf paths in any order.
A leaf is a node with no children.
What is the definition of a leaf node? A leaf node is a node that has no left or right child.
What should the output look like? The output should be a list of strings where each string represents a path from the root to a leaf node.
Are there any constraints on the tree?
[1, 100]
.-100
and 100
.#include <iostream>
#include <vector>
#include <string>
using namespace std;
// Definition for a binary tree node.
struct TreeNode {
int val;
TreeNode *left;
TreeNode *right;
TreeNode() : val(0), left(nullptr), right(nullptr) {}
TreeNode(int x) : val(x), left(nullptr), right(nullptr) {}
TreeNode(int x, TreeNode *left, TreeNode *right) : val(x), left(left), right(right) {}
};
class Solution {
public:
vector<string> binaryTreePaths(TreeNode* root) {
vector<string> result;
if (root) {
findPaths(root, "", result);
}
return result;
}
private:
void findPaths(TreeNode* node, string path, vector<string>& result) {
if (node) {
path += to_string(node->val);
// If it's a leaf, add the path to result
if (!node->left && !node->right) {
result.push_back(path);
} else {
path += "->"; // Add delimiter
if (node->left) {
findPaths(node->left, path, result);
}
if (node->right) {
findPaths(node->right, path, result);
}
}
}
}
};
This strategy ensures that all paths from the root to the leaves are found and formatted correctly.
Got blindsided by a question you didn’t expect?
Spend too much time studying?
Or simply don’t have the time to go over all 3000 questions?